• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyaudio.get_sample_size函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyaudio.get_sample_size函数的典型用法代码示例。如果您正苦于以下问题:Python get_sample_size函数的具体用法?Python get_sample_size怎么用?Python get_sample_size使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_sample_size函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

	def __init__(self, device_index = None):
		self.format = pyaudio.paInt16
		self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.format)
		self.CHUNK = 1024

		self.audio = None
		self.stream = None
开发者ID:YoungB2,项目名称:BatSignal,代码行数:7,代码来源:sensor.py


示例2: __init__

    def __init__(self, byte_data, sample_rate, bit_width, channels, dtype = None):
        """
        byte_data: A byte string containing the raw data.
        BIT_WIDTH: bit width in bytes.
        """
        
        assert isinstance(bit_width, (int, long)) and bit_width > 0, \
                "`bit_width` must be positive integer."
        bit_width = pyaudio.get_sample_size(pyaudio.get_format_from_width(bit_width))
        
        assert isinstance(channels, int) and channels in [1, 2], \
                "`channels` can be either 1(mono) or 2(stereo)."
        assert channels in (1, 2), \
                "`channels` can be either 1(mono) or 2(stereo) only."
        
        assert sample_rate > 0, "`sample_rate` must be positive."

        self.__bit_width = bit_width
        self.__channels = channels
        self.__sample_rate = sample_rate
        self.__byte_data = byte_data # a byte string

        if dtype is None:
            dtype = self._get_dtype_by_bit_width()

        if not self._validate_dtype(dtype):
            raise ValueError("`dtype` is not compatible with the `bit_width`.")

        self.__dtype = dtype
        self.format = pyaudio.get_format_from_width(self.BIT_WIDTH)
开发者ID:dboyliao,项目名称:pyaudio_wrapper,代码行数:30,代码来源:audio_data.py


示例3: pyaudio_scb

 def pyaudio_scb(self, rate, fmt=pyaudio.paInt16):
     samp_size = pyaudio.get_sample_size(fmt)
     maxint = (1 << (8*samp_size)) - 1
     dtype = ['!', 'h', 'i', '!', 'l', '!', '!', '!', 'q'][samp_size]
     def __callback(data, frames, time, status, self=self, rate=rate, maxint=maxint, dtype=dtype):
         return struct.pack(dtype*frames, *[maxint*int(i) for i in self.data(frames, self.freq, rate)])
     return __callback
开发者ID:Grissess,项目名称:itl_chorus,代码行数:7,代码来源:voice.py


示例4: __init__

    def __init__(self, recognizer, agent):
        super(Listener, self).__init__()

        self.recognizer = recognizer
        self.agent = agent
        self.queue = Queue.Queue()
        self.running = True

        self.sample_rate = 16000
        self.sample_width = pyaudio.get_sample_size(pyaudio.paInt16) * 1
        self.channels = 1

        config = Decoder.default_config()
        config.set_string('-hmm', path.join(PS_MODEL_DIR, 'en-us/en-us'))
        config.set_string('-lm', path.join(PS_MODEL_DIR, 'en-us/en-us.lm.dmp'))
        config.set_string('-dict', path.join(DATA_DIR, 'pocketsphinx/model/en-us/victoria-en-us.dict'))
        config.set_string('-logfn', 'NUL')
        config.set_string('-keyphrase', KEY_PHRASE)
        config.set_float('-samprate', self.sample_rate)
        config.set_float('-kws_threshold', 1e-40)

        self.decoder = Decoder(config)
        self.decoder.start_utt()

        self.frames = collections.deque()
        self.listening = -1
        self.silence_start = -1
        self.last_logged_hyp = None
开发者ID:Bakkes,项目名称:HeyVictoria,代码行数:28,代码来源:listener.py


示例5: activeListenToAllOptions

    def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True, MUSIC=False):
        """
            Records until a second of silence or times out after 12 seconds

            Returns a list of the matching options or None
        """

        RATE = 16000
        CHUNK = 1024
        LISTEN_TIME = 12

        # check if no threshold provided
        if THRESHOLD == None:
            THRESHOLD = self.fetchThreshold()

        self.speaker.play(jasperpath.data('audio', 'beep_hi.wav'))

        # prepare recording stream
        stream = self._audio.open(format=pyaudio.paInt16,
                            channels=1,
                            rate=RATE,
                            input=True,
                            frames_per_buffer=CHUNK)

        frames = []
        # increasing the range # results in longer pause after command generation
        lastN = [THRESHOLD * 1.2 for i in range(30)]

        for i in range(0, RATE / CHUNK * LISTEN_TIME):

            data = stream.read(CHUNK)
            frames.append(data)
            score = self.getScore(data)

            lastN.pop(0)
            lastN.append(score)

            average = sum(lastN) / float(len(lastN))

            # TODO: 0.8 should not be a MAGIC NUMBER!
            if average < THRESHOLD * 0.8:
                break

        self.speaker.play(jasperpath.data('audio', 'beep_lo.wav'))

        # save the audio data
        stream.stop_stream()
        stream.close()

        with tempfile.SpooledTemporaryFile(mode='w+b') as f:
            wav_fp = wave.open(f, 'wb')
            wav_fp.setnchannels(1)
            wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
            wav_fp.setframerate(RATE)
            wav_fp.writeframes(''.join(frames))
            wav_fp.close()
            f.seek(0)
            mode = TranscriptionMode.MUSIC if MUSIC else TranscriptionMode.NORMAL
            transcribed = self.active_stt_engine.transcribe(f, mode=mode)
        return transcribed
开发者ID:Koboldthegreat,项目名称:STEVE-client,代码行数:60,代码来源:mic.py


示例6: __init__

    def __init__(self):

        self.CHUNK = 1024
        self.RATE = 16000
        self.FORMAT = pyaudio.paInt16
        self.DTYPE='Int16'
        self.CHANNELS = 1

        self.RUN_SECONDS = 1000

        self.sampwidth = pyaudio.get_sample_size(self.FORMAT)

        self.mic = False
        self.wf = None

        self.deque_time = deque(maxlen=20)
        self.deque_mean = deque(maxlen=3)
        self.deque_freq = deque(maxlen=3)

        self.posneg_frequencies = np.fft.fftfreq(self.CHUNK, 1.0/self.RATE) 
        self.freqs_indices = np.where(self.posneg_frequencies >= 0)
        self.freqs = self.posneg_frequencies[np.where(self.posneg_frequencies >= 0)]

        self.t0 = time.time()
        self.ichunk = 0

        # plt.ion()
        # plt.axis([0,100,0,800])
        # fig=plt.figure()

        if RPI:
            self.led = Lights()
            self.led.start()
开发者ID:Amarang,项目名称:navsa,代码行数:33,代码来源:Music.py


示例7: __init__

    def __init__(self, wrapped_stream, format, muted=False):
        assert wrapped_stream is not None
        self.wrapped_stream = wrapped_stream
        self.muted = muted

        self.SAMPLE_WIDTH = pyaudio.get_sample_size(format)
        self.muted_buffer = b''.join([b'\x00' * self.SAMPLE_WIDTH])
开发者ID:Dark5ide,项目名称:mycroft-core,代码行数:7,代码来源:mic.py


示例8: __init__

    def __init__(self, device_index, sample_rate, bit_width, chunk_size = 8092, channels = 1):

        audio = pyaudio.PyAudio()
        ## Checking the device_index is valid or not.
        assert isinstance(device_index, (int, long)), "Device index must be an integer."
        device_count = audio.get_device_count()
        assert 0 <= device_index < device_count, "`device_index` out of range: {} out of {}".format(device_index, count)
        audio.terminate()
        self.__device_index = device_index

        if not self.device_info["maxInputChannels"] > 0:
            raise DeviceTypeError("Can not source from a non-input device.")

        self.__format = pyaudio.get_format_from_width(bit_width)
        self.__bit_width = pyaudio.get_sample_size(self.FORMAT)

        assert isinstance(sample_rate, (int, long)), "`sample_rate` must be integer."
        
        max_sample_rate = self.device_info["defaultSampleRate"]
        assert 0 < sample_rate <= max_sample_rate, "`sample_rate` out of range: {} out of {}".format(sample_rate, max_sample_rate)
        self.__sample_rate = sample_rate

        assert isinstance(chunk_size, (int, long)), "`chunk_size` must be integer."
        self.__chunk_size = chunk_size

        assert channels in [1, 2], '`channels` can be either 1 or 2. 1 for mono audio, 2 for stereo.' 
        self.__channels = channels

        # audio resource and streams.
        self.__audio = None
        self.__input_stream = None
开发者ID:dboyliao,项目名称:pyaudio_wrapper,代码行数:31,代码来源:source.py


示例9: save_audio

 def save_audio(self, fp, frames):
     sample_width = pyaudio.get_sample_size(self.format)
     f = open_audio(fp, 'wb')
     f.setsampwidth(sample_width)
     f.setframerate(self.rate)
     f.setnchannels(1)
     f.writeframes(''.join(frames))
     f.close()
开发者ID:brunoChr,项目名称:jasper-client,代码行数:8,代码来源:mic.py


示例10: write_chunks

def write_chunks(path, frames, rate=44100, channels=2, format=pyaudio.paInt16):
    """ write audio to hard disk """
    
    wf = wave.open(path, "wb")
    wf.setnchannels(channels)
    wf.setsampwidth(pyaudio.get_sample_size(format))
    wf.setframerate(rate)
    wf.writeframes(b"".join(frames))
    wf.close()
开发者ID:fzalkow,项目名称:DrumApp,代码行数:9,代码来源:audioio.py


示例11: __init__

        def __init__(self, device_index = None):
            self.device_index = device_index
            self.format = pyaudio.paInt16 # 16-bit int sampling
            self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.format)
            self.RATE = 16000 # sampling rate in Hertz
            self.CHANNELS = 1 # mono audio
            self.CHUNK = 1024 # number of frames stored in each buffer

            self.audio = None
            self.stream = None
开发者ID:Ashwaray,项目名称:Games,代码行数:10,代码来源:__init__.py


示例12: write_wave

def write_wave(arrs, filepath,
               sample_width=pyaudio.get_sample_size(PYAUDIO_FORMAT),
               channels=CHANNELS, sample_rate=SAMPLE_RATE):
    f = wave.open(filepath, 'w')
    f.setnchannels(channels)
    f.setsampwidth(sample_width)
    f.setframerate(sample_rate)
    for arr in _structpack(arrs):
        f.writeframes(arr)
    f.close()
开发者ID:adgaudio,项目名称:Bin,代码行数:10,代码来源:audio_fun.py


示例13: __init__

        def __init__(self, device_index = None):
            self.device_index = device_index
            self.format = pyaudio.paInt16
            self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.format)
            self.RATE = 44100
            self.CHANNELS = 1
            self.CHUNK = 2205

            self.audio = None
            self.stream = None
开发者ID:dsemi,项目名称:PennAppsX,代码行数:10,代码来源:gSpeechAPI.py


示例14: passiveListen

    def passiveListen(self, persona):
        rate = self.PASSIVE_RATE
        chunk = self.PASSIVE_CHUNK
        LISTEN_TIME = 10

        THRESHOLD = self.THRESHOLD_MULTIPLIER * self.fetchThreshold()
        stream = self._audio.open(format=pyaudio.paInt16,
                                  channels=1,
                                  rate=rate,
                                  input=True,
                                  frames_per_buffer=chunk)
        frames = []
        didDetect = False

        for i in range(0, rate / chunk * LISTEN_TIME):

            data = stream.read(chunk)
            frames.append(data)
            score = self.getScore(data)

            if score > THRESHOLD:
                didDetect = True
                break

        # no use continuing if no flag raised
        if not didDetect:
            print "No disturbance detected"
            stream.stop_stream()
            stream.close()
            return (None, None)

        # cutoff any recording before this disturbance was detected
        frames = frames[-20:]

        # otherwise, let's keep recording for few seconds and save the file
        DELAY_MULTIPLIER = 1.5
        for i in range(0, rate / chunk * DELAY_MULTIPLIER):
            data = stream.read(chunk)
            frames.append(data)

        with tempfile.NamedTemporaryFile(mode='w+b') as f:
            wav_fp = wave.open(f, 'wb')
            wav_fp.setnchannels(1)
            wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
            wav_fp.setframerate(rate)
            wav_fp.writeframes(''.join(frames))
            wav_fp.close()
            f.seek(0)
            # check if PERSONA was said
            transcribed = self.passive_transcribe(f)

        if any(persona in phrase for phrase in transcribed):
            return (THRESHOLD, persona)

        return (False, transcribed)
开发者ID:saarthaks,项目名称:just-another-AI,代码行数:55,代码来源:speaker.py


示例15: __init__

    def __init__(self, hmm_type=1, vad_threshold=3.5, pl_window=10, wip=1e-4, 
                  silprob=0.3, bestpath=True, remove_dc=True, do_keyphrase=False, keyphrase="NAVSA", kws_threshold=1e-4):

        self.CHUNK = 1024
        self.RATE = 16000
        self.FORMAT = pyaudio.paInt16
        self.CHANNELS = 1

        self.RUN_SECONDS = 1000

        self.sampwidth = pyaudio.get_sample_size(self.FORMAT)

        self.do_trigger = False

        # Create a decoder with certain model
        self.config = Decoder.default_config()

        if hmm_type == 0:
            self.config.set_string('-hmm', '/usr/local/share/pocketsphinx/model/en-us/en-us')
        elif hmm_type == 1:
            self.config.set_string('-hmm', 'model/cmusphinx-en-us-5.2')

        self.config.set_string('-dict', 'model/7705.dic')

        if do_keyphrase:
            self.config.set_string('-keyphrase', keyphrase)
            self.config.set_float('-kws_threshold', kws_threshold)
        else:
            self.config.set_string('-lm', 'model/7705.lm')


        self.config.set_string('-logfn', '/dev/null')
        self.config.set_string('-debug', '1')

        # http://cmusphinx.sourceforge.net/wiki/pocketsphinxhandhelds
        self.config.set_boolean('-bestpath', bestpath) # default is true
        self.config.set_float('-vad_threshold', vad_threshold) # default is 2
        self.config.set_float("-pl_window", pl_window) # default is 5, range is 0 to 10
        self.config.set_float('-wip', wip) #  0.005           Silence word transition probability
        self.config.set_float('-silprob', silprob) # 0.65            Word insertion penalty
        self.config.set_string('-remove_dc', 'yes' if remove_dc else 'no')

        self.decoder = Decoder(self.config)

        self.deque_time = deque(maxlen=20)
        self.deque_mean = deque(maxlen=50)

        self.mic = False
        self.wf = None
        self.vad = False
        self.rec_trigger = False
        self.rec_frames = []
        self.sec_since_kw = 999.9
        self.sec_since_vad = 999.9
开发者ID:Amarang,项目名称:navsa,代码行数:54,代码来源:sphinx_callback.py


示例16: read

 def read(self, buf, source_channels):
     source_sample_width = pyaudio.get_sample_size(pyaudio.paInt16) * source_channels
     audio = buf[3:]
     try:
         # sometimes the data received is incomplete so reusing state
         # data from ratecv() sometimes results in errors
         (audio, _) = audioop.ratecv(audio, source_sample_width, source_channels, 48000, self.listener.sample_rate, None)
         audio = audioop.tomono(audio, self.listener.sample_width, 0.5, 0.5)
         self.listener.read(audio)
     except audioop.error, e:
         logger.warn("Error preparing sample", exc_info=True)
开发者ID:Bakkes,项目名称:HeyVictoria,代码行数:11,代码来源:server.py


示例17: activeListenToAllOptions

  def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True,
                               MUSIC=False):
    """
        Records until a second of silence or times out after 12 seconds
        Returns a list of the matching options or None
    """

    # check if no threshold provided
    if THRESHOLD is None:
      THRESHOLD = self.fetchThreshold()

    playing = 'playing' in check_output(['mpc', '-h', '[email protected]']).split('\n')[1]
    if playing:
      call(['mpc', '-h', '[email protected]', 'pause'])

    # self.speaker.play(jasperpath.data('audio', 'beep_hi.wav'))
    self.say(random.choice(BEFORE))

    frames = []
    # increasing the range # results in longer pause after command
    # generation
    lastN = [THRESHOLD * 1.2 for i in range(30)]

    for i in range(0, RATE / CHUNK * LISTEN_TIME):

      data = self.queue.get()
      frames.append(data)
      score = self.getScore(data)

      lastN.pop(0)
      lastN.append(score)

      average = sum(lastN) / float(len(lastN))

      # TODO: 0.8 should not be a MAGIC NUMBER!
      if average < THRESHOLD * 0.8:
        break

    # self.speaker.play(jasperpath.data('audio', 'beep_lo.wav'))
    self.say(random.choice(AFTER))

    if playing:
      call(['mpc', '-h', '[email protected]', 'play'])

    # save the audio data
    with tempfile.SpooledTemporaryFile(mode='w+b') as f:
      wav_fp = wave.open(f, 'wb')
      wav_fp.setnchannels(1)
      wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
      wav_fp.setframerate(RATE)
      wav_fp.writeframes(''.join(frames))
      wav_fp.close()
      f.seek(0)
      return self.active_stt_engine.transcribe(f)
开发者ID:anfreita,项目名称:jasper-client,代码行数:54,代码来源:server.py


示例18: __init__

        def __init__(self, device_index = None):
            assert device_index is None or isinstance(device_index, int), "Device index must be None or an integer"
            self.device_index = device_index
            self.format = pyaudio.paInt16 # 16-bit int sampling
            self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.format)
            self.RATE = 16000 # sampling rate in Hertz
            self.CHANNELS = 1 # mono audio
            self.CHUNK = 1024 # number of frames stored in each buffer

            self.audio = None
            self.stream = None
开发者ID:kevinismith,项目名称:speech_recognition,代码行数:11,代码来源:__init__.py


示例19: __init__

        def __init__(self, device_index = None):
            assert device_index is None or isinstance(device_index, int), "Device index must be None or an integer"
            if device_index is not None: # ensure device index is in range
                audio = pyaudio.PyAudio(); count = audio.get_device_count(); audio.terminate() # obtain device count
                assert 0 <= device_index < count, "Device index out of range"
            self.device_index = device_index
            self.format = pyaudio.paInt16 # 16-bit int sampling
            self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.format)
            self.RATE = 16000 # sampling rate in Hertz
            self.CHANNELS = 1 # mono audio
            self.CHUNK = 1024 # number of frames stored in each buffer

            self.audio = None
            self.stream = None
开发者ID:eclubiitk,项目名称:ZIZO101,代码行数:14,代码来源:__init__.py


示例20: __init__

  def __init__(self):
    self.CHUNK = 1024
    self.FORMAT = pyaudio.paInt16
    self.CHANNELS = 2
    self.RATE = 44100
    self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.FORMAT)

    self.energy_threshold = 1500
    self.pause_threshold = 0.8
    self.quiet_duration = 0.5

    self.seconds_per_buffer = self.CHUNK / self.RATE
    self.pause_buffer_count = math.ceil(self.pause_threshold / self.seconds_per_buffer)
    self.quiet_buffer_count = math.ceil(self.quiet_duration / self.seconds_per_buffer)
开发者ID:ananko,项目名称:speech_box,代码行数:14,代码来源:demo.py



注:本文中的pyaudio.get_sample_size函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyaudio.PyAudio类代码示例发布时间:2022-05-25
下一篇:
Python pyatspi.Registry类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap