Python pyaudio.paInt16() Examples

The following are 30 code examples of pyaudio.paInt16(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyaudio , or try the search function .
Example #1
Source File: proj2_yt_mvp.py    From ai-makers-kit with MIT License 13 votes vote down vote up
def __enter__(self):
		self._audio_interface = pyaudio.PyAudio()
		self._audio_stream = self._audio_interface.open(
			format=pyaudio.paInt16,
			channels=1, rate=self._rate,
			input=True, frames_per_buffer=self._chunk,
			# Run the audio stream asynchronously to fill the buffer object.
			# This is necessary so that the input device's buffer doesn't
			# overflow while the calling thread makes network requests, etc.
			stream_callback=self._fill_buffer,
		)

		self.closed = False

		return self

	#def __exit__(self, type, value, traceback): 
Example #2
Source File: vad.py    From audio with BSD 2-Clause "Simplified" License 11 votes vote down vote up
def __enter__(self):
        self._audio_interface = pyaudio.PyAudio()
        self._audio_stream = self._audio_interface.open(
            # format=pyaudio.paInt16,
            format=pyaudio.paFloat32,
            # The API currently only supports 1-channel (mono) audio
            # https://goo.gl/z757pE
            channels=1,
            rate=self._rate,
            input=True,
            frames_per_buffer=self._chunk,
            input_device_index=self._device,
            # Run the audio stream asynchronously to fill the buffer object.
            # This is necessary so that the input device's buffer doesn't
            # overflow while the calling thread makes network requests, etc.
            stream_callback=self._fill_buffer,
        )

        self.closed = False

        return self 
Example #3
Source File: google_client.py    From dialogflow_ros with MIT License 9 votes vote down vote up
def __init__(self):
        # Audio stream input setup
        FORMAT = pyaudio.paInt16
        CHANNELS = 1
        RATE = 16000
        self.CHUNK = 4096
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=FORMAT, channels=CHANNELS,
                                      rate=RATE, input=True,
                                      frames_per_buffer=self.CHUNK,
                                      stream_callback=self.get_data)
        self._buff = Queue.Queue()  # Buffer to hold audio data
        self.closed = False

        # ROS Text Publisher
        self.text_pub = rospy.Publisher('/google_client/text', String, queue_size=10)

        # Context clues in yaml file
        rospack = rospkg.RosPack()
        yamlFileDir = rospack.get_path('dialogflow_ros') + '/config/context.yaml'
        with open(yamlFileDir, 'r') as f:
            self.context = yaml.load(f) 
Example #4
Source File: smart_trash_can.py    From ai-makers-kit with MIT License 7 votes vote down vote up
def __enter__(self):
		self._audio_interface = pyaudio.PyAudio()
		self._audio_stream = self._audio_interface.open(
			format=pyaudio.paInt16,
			channels=1, rate=self._rate,
			input=True, frames_per_buffer=self._chunk,
			# Run the audio stream asynchronously to fill the buffer object.
			# This is necessary so that the input device's buffer doesn't
			# overflow while the calling thread makes network requests, etc.
			stream_callback=self._fill_buffer,
		)

		self.closed = False

		return self

	#def __exit__(self, type, value, traceback): 
Example #5
Source File: proj3_capital_game.py    From ai-makers-kit with MIT License 7 votes vote down vote up
def __enter__(self):
		self._audio_interface = pyaudio.PyAudio()
		self._audio_stream = self._audio_interface.open(
			format=pyaudio.paInt16,
			channels=1, rate=self._rate,
			input=True, frames_per_buffer=self._chunk,
			# Run the audio stream asynchronously to fill the buffer object.
			# This is necessary so that the input device's buffer doesn't
			# overflow while the calling thread makes network requests, etc.
			stream_callback=self._fill_buffer,
		)

		self.closed = False

		return self

	#def __exit__(self, type, value, traceback): 
Example #6
Source File: transcribe_streaming_mic.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def __enter__(self):
        self._audio_interface = pyaudio.PyAudio()
        self._audio_stream = self._audio_interface.open(
            format=pyaudio.paInt16,
            # The API currently only supports 1-channel (mono) audio
            # https://goo.gl/z757pE
            channels=1, rate=self._rate,
            input=True, frames_per_buffer=self._chunk,
            # Run the audio stream asynchronously to fill the buffer object.
            # This is necessary so that the input device's buffer doesn't
            # overflow while the calling thread makes network requests, etc.
            stream_callback=self._fill_buffer,
        )

        self.closed = False

        return self 
Example #7
Source File: microphone.py    From audio-reactive-led-strip with MIT License 6 votes vote down vote up
def start_stream(callback):
    p = pyaudio.PyAudio()
    frames_per_buffer = int(config.MIC_RATE / config.FPS)
    stream = p.open(format=pyaudio.paInt16,
                    channels=1,
                    rate=config.MIC_RATE,
                    input=True,
                    frames_per_buffer=frames_per_buffer)
    overflows = 0
    prev_ovf_time = time.time()
    while True:
        try:
            y = np.fromstring(stream.read(frames_per_buffer, exception_on_overflow=False), dtype=np.int16)
            y = y.astype(np.float32)
            stream.read(stream.get_read_available(), exception_on_overflow=False)
            callback(y)
        except IOError:
            overflows += 1
            if time.time() > prev_ovf_time + 1:
                prev_ovf_time = time.time()
                print('Audio buffer has overflowed {} times'.format(overflows))
    stream.stop_stream()
    stream.close()
    p.terminate() 
Example #8
Source File: recorder.py    From gif-music-visualizer with GNU General Public License v3.0 6 votes vote down vote up
def setup(self):
        """initialize sound card."""
        #TODO - windows detection vs. alsa or something for linux
        #TODO - try/except for sound card selection/initiation

        self.buffersToRecord=int(self.RATE*self.secToRecord/self.BUFFERSIZE)
        if self.buffersToRecord==0: self.buffersToRecord=1
        self.samplesToRecord=int(self.BUFFERSIZE*self.buffersToRecord)
        self.chunksToRecord=int(self.samplesToRecord/self.BUFFERSIZE)
        self.secPerPoint=1.0/self.RATE

        self.p = pyaudio.PyAudio()
        self.inStream = self.p.open(format=pyaudio.paInt16,channels=1,rate=self.RATE,input=True,frames_per_buffer=self.BUFFERSIZE)

        self.xsBuffer=numpy.arange(self.BUFFERSIZE)*self.secPerPoint
        self.xs=numpy.arange(self.chunksToRecord*self.BUFFERSIZE)*self.secPerPoint
        self.audio=numpy.empty((self.chunksToRecord*self.BUFFERSIZE),dtype=numpy.int16) 
Example #9
Source File: audio.py    From Oe2sSLE with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, data, fmt):

        if fmt.formatTag != RIFF.WAVE_fmt_.WAVE_FORMAT_PCM:
            raise Exception()

        if fmt.samplesPerSec < 1000 or fmt.samplesPerSec > 192000:
            data, fmt = wav_tools.wav_resample_preview(data, fmt, 1000, 192000)
        self.data = data
        self.fmt = fmt
        self._offset = 0

        def callback(indata, frames, time, status):
            n_bytes=frames*fmt.blockAlign
            to_read=min(n_bytes, len(self.data) - self._offset)
            outdata = self.data[self._offset:self._offset+to_read]
            self._offset += to_read
            return (outdata,pa.paContinue)

        self.stream = audio.open(format=pa.paInt16, channels=fmt.channels, rate=fmt.samplesPerSec, output=True, stream_callback=callback) 
Example #10
Source File: proj2_yt_mvp.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def __enter__(self):
		self._audio_interface = pyaudio.PyAudio()
		self._audio_stream = self._audio_interface.open(
			format=pyaudio.paInt16,
			channels=1, rate=self._rate,
			input=True, frames_per_buffer=self._chunk,
			# Run the audio stream asynchronously to fill the buffer object.
			# This is necessary so that the input device's buffer doesn't
			# overflow while the calling thread makes network requests, etc.
			stream_callback=self._fill_buffer,
		)

		self.closed = False

		return self

	#def __exit__(self, type, value, traceback): 
Example #11
Source File: audiostream.py    From rtmonoaudio2midi with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        pya = PyAudio()
        self._stream = pya.open(
            format=paInt16,
            channels=1,
            rate=SAMPLE_RATE,
            input=True,
            frames_per_buffer=WINDOW_SIZE,
            stream_callback=self._process_frame,
        )
        self._stream.start_stream()

        while self._stream.is_active() and not raw_input():
            time.sleep(0.1)

        self._stream.stop_stream()
        self._stream.close()
        pya.terminate() 
Example #12
Source File: smart_trash_can.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def __enter__(self):
		self._audio_interface = pyaudio.PyAudio()
		self._audio_stream = self._audio_interface.open(
			format=pyaudio.paInt16,
			channels=1, rate=self._rate,
			input=True, frames_per_buffer=self._chunk,
			# Run the audio stream asynchronously to fill the buffer object.
			# This is necessary so that the input device's buffer doesn't
			# overflow while the calling thread makes network requests, etc.
			stream_callback=self._fill_buffer,
		)

		self.closed = False

		return self

	#def __exit__(self, type, value, traceback): 
Example #13
Source File: main.py    From real-time-plot-microphone-kivy with MIT License 6 votes vote down vote up
def get_microphone_level():
    """
    source: http://stackoverflow.com/questions/26478315/getting-volume-levels-from-pyaudio-for-use-in-arduino
    audioop.max alternative to audioop.rms
    """
    chunk = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 44100
    p = pyaudio.PyAudio()

    s = p.open(format=FORMAT,
               channels=CHANNELS,
               rate=RATE,
               input=True,
               frames_per_buffer=chunk)
    global levels
    while True:
        data = s.read(chunk)
        mx = audioop.rms(data, 2)
        if len(levels) >= 100:
            levels = []
        levels.append(mx) 
Example #14
Source File: mic_client.py    From dialogflow_ros with MIT License 6 votes vote down vote up
def __init__(self):
        # Audio stream input setup
        FORMAT = pyaudio.paInt16
        CHANNELS = 1
        RATE = 16000
        self.CHUNK = 4096
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=FORMAT, channels=CHANNELS,
                                      rate=RATE, input=True,
                                      frames_per_buffer=self.CHUNK,
                                      stream_callback=self._get_data)
        self._buff = Queue.Queue()  # Buffer to hold audio data
        self.closed = False

        # ROS Text Publisher
        text_topic = rospy.get_param('/text_topic', '/dialogflow_text')
        self.text_pub = rospy.Publisher(text_topic, String, queue_size=10) 
Example #15
Source File: cross_record.py    From nyumaya_audio_recognition with Apache License 2.0 6 votes vote down vote up
def run(self):
		self.mic_stream = self.p.open(format=pyaudio.paInt16,
			channels=self.channels,
			rate=self.sample_rate,
			input=True,
			frames_per_buffer=self.blocksize)
			
		self.running = True
		while self.mic_stream and self.running:
			input_data = self.mic_stream.read(self.blocksize)
			if input_data:
				self.audio_buffer.write(input_data)

		#Shutdown record command
		if(self.mic_stream):
			self.mic_stream.close()
			self.mic_stream = None 
Example #16
Source File: demo_client.py    From ZASR_tensorflow with Apache License 2.0 6 votes vote down vote up
def main():
    # prepare audio recorder
    p = pyaudio.PyAudio()
    stream = p.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=16000,
        input=True,
        stream_callback=callback)
    stream.start_stream()

    # prepare keyboard listener
    with keyboard.Listener(
            on_press=on_press, on_release=on_release) as listener:
        listener.join()

    # close up
    stream.stop_stream()
    stream.close()
    p.terminate() 
Example #17
Source File: offline_ser.py    From LIVE_SER with Apache License 2.0 6 votes vote down vote up
def predict_file(dec, pyaudio, path, frames, args, rate = 16000, format = pyaudio.paInt16, save = False):
    wf = wave.open(path, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(pyaudio.get_sample_size(format))
    wf.setframerate(rate)
    #this code works for only for pulseaudio
    #wf.writeframes(b''.join(frames))
    wf.writeframes(frames)
    wf.close()

    results = dec.predict_file(path, feat_mode = args.feat_mode, feat_dim = args.feat_dim, three_d = args.three_d)
    
    if save == False:
        os.remove(path)
    if args.predict_mode == 0:
        task_outputs = dec.returnDiff(results)
    elif args.predict_mode == 1:
        task_outputs = dec.returnLabel(results)
    else:
        task_outputs = dec.returnClassDist(results)
    return task_outputs

#main loop for speech emotion recognition 
Example #18
Source File: AVrecordeR.py    From AVrecordeR with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
        
        self.open = True
        self.rate = 44100
        self.frames_per_buffer = 1024
        self.channels = 2
        self.format = pyaudio.paInt16
        self.audio_filename = "temp_audio.wav"
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=self.format,
                                      channels=self.channels,
                                      rate=self.rate,
                                      input=True,
                                      frames_per_buffer = self.frames_per_buffer)
        self.audio_frames = []


    # Audio starts being recorded 
Example #19
Source File: core_recorder.py    From rcaudio with MIT License 6 votes vote down vote up
def run(self):
        self.logger.debug("Start to recording...")
        self.logger.debug("  Time = %s"%self.time)
        self.logger.debug("  Sample Rate = %s"%self.sr)
        self.start_time = time.time()
        pa=PyAudio()
        stream=pa.open(format = paInt16,channels=1, rate=self.sr,input=True, frames_per_buffer=self.frames_per_buffer)
        my_buf=[]
        count=0
        if self.time is None:
            total_count = 1e10
        else:
            total_count = self.time * self.sr / self.batch_num
        while count< total_count and self.__running.isSet():
            datawav = stream.read(self.batch_num, exception_on_overflow = True)
            datause = np.fromstring(datawav,dtype = np.short)
            for w in datause:
                self.buffer.put(w)
            count+=1
        stream.close() 
Example #20
Source File: core_recorder.py    From rcaudio with MIT License 6 votes vote down vote up
def run(self):
        self.logger.debug("Start to recording...")
        self.logger.debug("  Time = %s"%self.time)
        self.logger.debug("  Sample Rate = %s"%self.sr)
        self.start_time = time.time()
        pa=PyAudio()
        stream=pa.open(format = paInt16,channels=1, rate=self.sr,input=True, frames_per_buffer=self.frames_per_buffer)
        my_buf=[]
        count=0
        if self.time is None:
            total_count = 1e10
        else:
            total_count = self.time * self.sr / self.batch_num
        while count< total_count and self.__running.isSet():
            datawav = stream.read(self.batch_num, exception_on_overflow = True)
            datause = np.fromstring(datawav,dtype = np.short)
            for w in datause:
                self.buffer.put(w)
            count+=1
        stream.close() 
Example #21
Source File: audio_server.py    From dialogflow_ros with MIT License 6 votes vote down vote up
def __init__(self):
        FORMAT = pyaudio.paInt16
        CHANNELS = 1
        RATE = 16000
        CHUNK = 4096
        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=FORMAT, channels=CHANNELS, rate=RATE,
                                      input=True, frames_per_buffer=CHUNK,
                                      stream_callback=self._callback)
        self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.read_list = [self.serversocket]

        self._server_name = rospy.get_param('/dialogflow_client/server_name',
                                            '127.0.0.1')
        self._port = rospy.get_param('/dialogflow_client/port', 4444)

        rospy.loginfo("DF_CLIENT: Audio Server Started!") 
Example #22
Source File: main.py    From Systematic-LEDs with MIT License 6 votes vote down vote up
def startStream(self):
        self.stream = py_audio.open(format = pyaudio.paInt16,
                                    channels = 1,
                                    rate = self.device_rate,
                                    input = True,
                                    input_device_index = self.device_id,
                                    frames_per_buffer = self.frames_per_buffer)
            
        # overflows = 0
        # prev_ovf_time = time.time()
        while True:
            try:
                y = np.fromstring(self.stream.read(self.frames_per_buffer), dtype=np.int16)
                y = y.astype(np.float32)
                self.callback_func(y)
            except IOError:
                pass
                # overflows += 1
                # if time.time() > prev_ovf_time + 1:
                #     prev_ovf_time = time.time()
                #     if config.settings["configuration"]["USE_GUI"]:
                #         gui.label_error.setText('Audio buffer has overflowed {} times'.format(overflows))
                #     else:
                #         print('Audio buffer has overflowed {} times'.format(overflows)) 
Example #23
Source File: audio-gate-level.py    From silvius with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run_test(self):
        import pyaudio
        import audioop
        pa = pyaudio.PyAudio()
        sample_rate = self.byterate
        stream = None 
        
        while stream is None:
            try:
                # try adjusting this if you want fewer network packets
                self.chunk = 2048 * 2 * sample_rate / self.byterate

                mic = self.mic
                if mic == -1:
                    mic = pa.get_default_input_device_info()['index']
                    print >> sys.stderr, "Selecting default mic"
                print >> sys.stderr, "Using mic #", mic
                stream = pa.open(
                    rate = sample_rate,
                    format = pyaudio.paInt16,
                    channels = 1,
                    input = True,
                    input_device_index = mic,
                    frames_per_buffer = self.chunk)
            except IOError, e:
                if(e.errno == -9997 or e.errno == 'Invalid sample rate'):
                    new_sample_rate = int(pa.get_device_info_by_index(mic)['defaultSampleRate'])
                    if(sample_rate != new_sample_rate):
                        sample_rate = new_sample_rate
                        continue
                print >> sys.stderr, "\n", e
                print >> sys.stderr, "\nCould not open microphone. Please try a different device."
                global fatal_error
                fatal_error = True
                sys.exit(0) 
Example #24
Source File: view_with_band_pass_filter.py    From tdoa with Apache License 2.0 5 votes vote down vote up
def start(self, quit_event=None, show=None):
        stream = self.pyaudio_instance.open(
            rate=RATE,
            frames_per_buffer=FRAMES,
            format=pyaudio.paInt16,
            channels=2,
            input=True,
            # output_device_index=1,
            stream_callback=self._callback)

        self.event.clear()
        if not quit_event:
            quit_event = threading.Event()

        phat = [0] * (2 * direction_n + 1)
        while not (quit_event.is_set() or self.event.is_set()):
            try:
                data = self.queue.get()

                buf = np.fromstring(data, dtype='int16')
                tau, cc = gcc_phat(buf[0::2] * window, buf[1::2] * window, fs=RATE, max_tau=max_tau, interp=1)
                theta = math.asin(tau / max_tau) * 180 / math.pi
                print('\ntheta: {}'.format(int(theta)))

                for i, v in enumerate(cc):
                    phat[i] = int(v * 512)

                if show:
                    show(phat)
                # print [l for l in level]
            except KeyboardInterrupt:
                break

        stream.close() 
Example #25
Source File: __init__.py    From PyBaiduYuyin with MIT License 5 votes vote down vote up
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 
Example #26
Source File: mic.py    From silvius with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def opened(self):
        import pyaudio
        import audioop
        pa = pyaudio.PyAudio()
        sample_rate = self.byterate
        stream = None 
        
        while stream is None:
            try:
                # try adjusting this if you want fewer network packets
                self.chunk = 2048 * 2 * sample_rate / self.byterate

                mic = self.mic
                if mic == -1:
                    mic = pa.get_default_input_device_info()['index']
                    print >> sys.stderr, "Selecting default mic"
                print >> sys.stderr, "Using mic #", mic
                stream = pa.open(
                    rate = sample_rate,
                    format = pyaudio.paInt16,
                    channels = 1,
                    input = True,
                    input_device_index = mic,
                    frames_per_buffer = self.chunk)
            except IOError, e:
                if(e.errno == -9997 or e.errno == 'Invalid sample rate'):
                    new_sample_rate = int(pa.get_device_info_by_index(mic)['defaultSampleRate'])
                    if(sample_rate != new_sample_rate):
                        sample_rate = new_sample_rate
                        continue
                print >> sys.stderr, "\n", e
                print >> sys.stderr, "\nCould not open microphone. Please try a different device."
                global fatal_error
                fatal_error = True
                sys.exit(0) 
Example #27
Source File: translate_from_mic.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        self._audio_interface = pyaudio.PyAudio()
        self._audio_stream = self._audio_interface.open(
            format=pyaudio.paInt16,
            channels=1, rate=self._rate,
            input=True, frames_per_buffer=self._chunk,
            # Run the audio stream asynchronously to fill the buffer object.
            # This is necessary so that the input device's buffer doesn't
            # overflow while the calling thread makes network requests, etc.
            stream_callback=self._fill_buffer,
        )

        self.closed = False

        return self 
Example #28
Source File: mic_array.py    From mic_array with Apache License 2.0 5 votes vote down vote up
def __init__(self, rate=16000, channels=8, chunk_size=None):
        self.pyaudio_instance = pyaudio.PyAudio()
        self.queue = Queue.Queue()
        self.quit_event = threading.Event()
        self.channels = channels
        self.sample_rate = rate
        self.chunk_size = chunk_size if chunk_size else rate / 100

        device_index = None
        for i in range(self.pyaudio_instance.get_device_count()):
            dev = self.pyaudio_instance.get_device_info_by_index(i)
            name = dev['name'].encode('utf-8')
            print(i, name, dev['maxInputChannels'], dev['maxOutputChannels'])
            if dev['maxInputChannels'] == self.channels:
                print('Use {}'.format(name))
                device_index = i
                break

        if device_index is None:
            raise Exception('can not find input device with {} channel(s)'.format(self.channels))

        self.stream = self.pyaudio_instance.open(
            input=True,
            start=False,
            format=pyaudio.paInt16,
            channels=self.channels,
            rate=int(self.sample_rate),
            frames_per_buffer=int(self.chunk_size),
            stream_callback=self._callback,
            input_device_index=device_index,
        ) 
Example #29
Source File: alexa_audio_device_pyaduio.py    From AlexaDevice with MIT License 5 votes vote down vote up
def __init__(self):
		self.pa = pyaudio.PyAudio()
		self.in_stream = self.pa.open(format=pyaudio.paInt16, channels=1,
						rate=16000, input=True)
		self.in_stream.start_stream()
		self.out_stream = self.pa.open(format=pyaudio.paInt16, channels=1,
						rate=16000,	output=True)
		self.out_stream.start_stream() 
Example #30
Source File: system_eq.py    From BiblioPixelAnimations with MIT License 5 votes vote down vote up
def __init__(self, rate=8000, chunksize=128):
        self.rate = rate
        self.chunksize = chunksize
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(format=pyaudio.paInt16,
                                  channels=1,
                                  rate=self.rate,
                                  input=True,
                                  frames_per_buffer=self.chunksize,
                                  stream_callback=self.new_frame)
        self.lock = threading.Lock()
        self.stop = False
        self.frames = []