def audio_thread(): try: if self.samplewidth == 1: dtype = "int8" elif self.samplewidth == 2: dtype = "int16" elif self.samplewidth == 3: dtype = "int24" elif self.samplewidth == 4: dtype = "int32" else: raise ValueError("invalid sample width") self.stream = sounddevice.RawOutputStream( self.samplerate, channels=self.nchannels, dtype=dtype) self.stream.start() stream_ready.set() q = self.samp_queue try: while True: sample = q.get() if not sample: break sample.write_frames(self.stream) if self.played_callback: self.played_callback(sample) if q.empty(): time.sleep(sample.duration) self.all_played.set() finally: # self.stream.stop() causes pop self.stream.close() self.all_played.set() finally: pass
def run(self): print("[DEMOD] Starting.") self.running = True self.safed = False buff = np.zeros([self.dsp_buff], dtype=np.complex64) rx = self.sdr.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32) self.sdr.activateStream(rx) with sd.RawOutputStream(blocksize=self.dsp_out, callback=self.router, samplerate=self.afs, latency='high', channels=2): while self.running: for i in range(self.dsp_buff // self.sdr_buff): self.sdr.readStream(rx, [buff[(i * self.sdr_buff):]], self.sdr_buff, timeoutUs=int(1e9)) self.que.put(buff.astype(np.complex64)) with self.que.mutex: self.que.queue.clear() self.sdr.deactivateStream(rx) self.sdr.closeStream(rx) self.safed = True
def receive(self, listening_port, number_of_chunks_received): if __debug__: print(f"receive: listening_port={listening_port}") # UDP socket to receive self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) listening_endpoint = ("0.0.0.0", listening_port) self.sock.bind(listening_endpoint) def callback(outdata, frames, time, status): print(frames, time) assert frames == self.samples_per_chunk if status.output_underflow: print('Output underflow: increase blocksize?', file=sys.stderr) raise sd.CallbackAbort assert not status #print(sock) outdata, source_address = self.sock.recvfrom( Intercom.max_packet_size) number_of_chunks_received.value += 1 with sd.RawOutputStream(samplerate=self.samples_per_second, blocksize=self.samples_per_chunk, device=None, channels=self.number_of_channels, dtype=numpy.int16, callback=callback): while True: time.sleep(1)
def receive(self, listening_port, number_of_chunks_received): if __debug__: print(f"receive: listening_port={listening_port}") # UDP socket to receive self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) listening_endpoint = ("0.0.0.0", listening_port) self.sock.bind(listening_endpoint) def callback(outdata, frames, time, status): outdata, source_address = self.sock.recvfrom( Intercom.max_packet_size) number_of_chunks_received.value += 1 with sd.RawOutputStream(samplerate=self.samples_per_second, blocksize=self.samples_per_chunk, device=None, channels=self.number_of_channels, dtype=numpy.int16, callback=callback): while True: time.sleep(1) print("o") while True: callback(None, None, None, None)
def audio_thread() -> None: mixed_chunks = self.mixer.chunks() self.stream = sounddevice.RawOutputStream(self.samplerate, channels=self.nchannels, dtype=dtype) self.stream.start() thread_ready.set() try: silence = b"\0" * self.chunksize while True: data = next(mixed_chunks) or silence self.stream.write(data) if len(data) < self.chunksize: self.stream.write(silence[len(data):]) if self.playing_callback: sample = Sample.from_raw_frames( data, self.samplewidth, self.samplerate, self.nchannels) # type: ignore self.playing_callback(sample) except StopIteration: pass finally: self.stream.stop() self.stream.close() self.stream = None
def PLAY(): while True: if len(BUFFER) > 5: data = BUFFER[0] # get first paket from buffer # init outputstream take typw from first package seqnum, packet = rtp.getData(data) payloadtype = packet['payloadtype'] info = rtp.getPayloadInfos(payloadtype) print (' [PLAY] Payloadsize: {} Blocksize: {} Samplerate: {} Channel: {}'.format( PAKET_SIZE, args.blocksize, info['rate'], info['channels'])) with sd.RawOutputStream( device = args.device, samplerate = info['rate'], blocksize = args.blocksize, # its dtype = 'int16', # info['type'] channels = info['channels'], latency = 'high', # its to have on every device same latency callback = callback ): while FAIL_COUNTER < 1: # after 5 fails -> break pass else: pass
def start(self, send=True, receive=True): """ Start audio I/O stream and processing thread """ if receive: sd.check_input_settings(device=self.input_device, channels=1, dtype=self.sample_size, samplerate=self.sdk.sample_rate) self.processing = AudioProcessingThread(parent=self) self.input_stream = sd.RawInputStream(device=self.input_device, channels=1, samplerate=int( self.sdk.sample_rate), dtype=self.sample_size, blocksize=self.block_size, callback=self.process_input) self.input_stream.start() if send: sd.check_output_settings(device=self.output_device, channels=self.output_channels, dtype=self.sample_size, samplerate=self.sdk.sample_rate) self.output_stream = sd.RawOutputStream( device=self.output_device, channels=self.output_channels, samplerate=int(self.sdk.sample_rate), dtype=self.sample_size, blocksize=self.block_size, callback=self.process_output) self.output_stream.start()
def __init__(self, samplerate: int = 0, samplewidth: int = 0, nchannels: int = 0, frames_per_chunk: int = 0) -> None: super().__init__(samplerate, samplewidth, nchannels, frames_per_chunk, 0) global sounddevice import sounddevice if self.samplewidth == 1: dtype = "int8" elif self.samplewidth == 2: dtype = "int16" elif self.samplewidth == 3: dtype = "int24" elif self.samplewidth == 4: dtype = "int32" else: raise ValueError("invalid sample width") self._empty_sound_data = b"\0" * self.chunksize self.mixed_chunks = self.mixer.chunks() self.stream = sounddevice.RawOutputStream( self.samplerate, channels=self.nchannels, dtype=dtype, # type: ignore blocksize=self.frames_per_chunk, callback=self.streamcallback) self.stream.start()
def init_audio(d_out, frq): global stream back_up_config(frq) import sounddevice as sd sd.default.channels = 1 sd.default.dtype = 'int16' dev_index = -1 dev_freq = -1 if d_out == "stl_capture": device_name = "STL_playback" dev_index = sd.query_devices().index( sd.query_devices(device=device_name)) dev_freq = sd.query_devices( device="STL_playback")["default_samplerate"] print("DEVICE: {} INDEX: {} RATE: {}".format( device_name, dev_index, dev_freq)) print("{}MIC DEVICE: {} INDEX: {} RATE: {} CH: {}".format( T_COLOR.get('CYAN', ''), "STL_capture", sd.query_devices().index(sd.query_devices( device="STL_capture")), dev_freq, sd.default.channels) + ANSI_OFF) elif d_out == "alsa_playback": dev_index = sd.query_devices().index( sd.query_devices(device="default")) dev_freq = sd.query_devices( device="STL_playback")["default_samplerate"] print("DEVICE: {} INDEX: {} RATE: {}".format( sd.query_devices(device="default")["name"], dev_index, dev_freq)) sd.default.device = dev_index stream = sd.RawOutputStream(samplerate=dev_freq)
def init_audio(d_out, ff): global stream #make a backup of orginal configuration files call(["cp", "/home/pi/.asoundrc", "/home/pi/.asoundrc_bkp"]) call(["scp", "/etc/asound.conf", "/etc/asound_bkp.conf"]) if ff == 16000: call(["cp", "./asoundrc_template_16KHz", "/home/pi/.asoundrc"]) call(["scp", "./asoundrc_template_16KHz", "/etc/asound.conf"]) else: call(["cp", "./asoundrc_template_8KHz", "/home/pi/.asoundrc"]) call(["scp", "./asoundrc_template_8KHz", "/etc/asound.conf"]) import sounddevice as sd sd.default.channels=1 sd.default.dtype='int16' devIndex =-1 devF=-1 if d_out == "stl_capture": devIndex= sd.query_devices().index(sd.query_devices(device="STL_playback")) devF= sd.query_devices(device="STL_playback")["default_samplerate"] print("DEVICE: %s INDEX: %s RATE: %s " % ("STL_playback",devIndex, devF)) print(ANSI_CYAN + "MIC DEVICE: %s INDEX: %s RATE: %s CH: %s" % ("STL_capture",sd.query_devices().index(sd.query_devices(device="STL_capture")), devF, sd.default.channels[0])+ ANSI_OFF) if d_out == "alsa_playback": devIndex= sd.query_devices().index(sd.query_devices(device="default")) devF= sd.query_devices(device="STL_playback")["default_samplerate"] print("DEVICE: %s INDEX: %s RATE: %s " % (sd.query_devices(device="default")["name"],devIndex, devF)) sd.default.device=devIndex stream = sd.RawOutputStream(samplerate=devF)
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.morshu = Morshu() self.playing = False self._audio_buff_pos = 0 self._audio_buff_end = 0 self._sprite_frame = 0 self.frames = [] for i in range(154): self.frames.append(QPixmap(":/sprites/{}.png".format(i))) # current audio time in seconds self.audio_current_time = 0.0 # start audio stream self.audio_stream = sd.RawOutputStream(samplerate=18900, channels=1, dtype='int16', callback=self.stream_callback) self.ui.action_view_sprite.setChecked(True) self.ui.btn_load.clicked.connect(self.load_audio) self.ui.btn_play.clicked.connect(self.toggle_play) self.ui.slider.sliderMoved.connect(self.slider_moved) self.ui.action_github.triggered.connect(lambda: webbrowser.open("https://github.com/n0spaces/MorshuTalk/"))
def startPlay(self): self.outputStream = sd.RawOutputStream(channels=self.channels, samplerate=self.samples, device=self.outputDeviceName, dtype='int16', blocksize=240, callback=self.callbackOutput) self.outputStream.start()
def INIT(): global INITTIME # the simulated_max = 7 start = tz.time() # simulate receive and play for i in range(1,simulated_max): buffer = [] for i in range(1,5): data = b'\x00' * 4112 paket = rtp.createPacket(1,77777,1,data) seqnum, data = rtp.getData(paket) if data == 'WANNA HAVE THE RTT': pass else: buffer.append(data) outdata = [] seqnum, paket = rtp.getData(paket) data = paket['payload'] outdata[:] = data # put to stream FAIL_COUNTER = 0 # reset fails # open stream with sd.RawOutputStream( device = args.device, samplerate = 44100, blocksize = args.blocksize, # its dtype = 'int16', # info['type'] channels = 1, latency = 'high', # its to have on every device same latency callback = sim_callback ): while len(buffer) > 0: prev = buffer.pop(0) prev_len = len(prev) sd.stop() # sleep sound latency if not(args.device): device_latency = sd.query_devices(0)['default_high_output_latency'] else: device_latency = sd.query_devices(args.device)['default_high_output_latency'] tz.sleep(device_latency) end = tz.time() INITTIME = (end-start) #print (' [INIT] device latency: {}'.format(device_latency)) print (' [INIT] processing time: {}'.format(INITTIME+args.low))
def __init__(self, samplerate, blocksize, channels): self.queue = queue.Queue(maxsize=25) self.stream = sd.RawOutputStream(samplerate=samplerate, blocksize=blocksize, device="default", channels=channels, dtype='int16', latency='low', callback=self.callback, finished_callback=self.finished)
async def speaker(self, samplerate, dtype, blocksize, volume=None, *, request_stream): import sounddevice as sd loop = asyncio.get_running_loop() done_ev = asyncio.Event() def fcb(): self.mic_int = False self._speaker_power(None) loop.call_soon_threadsafe(done_ev.set) zeros = None def cb( outdata, frames, time, status ): # don't do time consuming await/future.result() in this callback nonlocal zeros # if status: # print('[speaker]', status) # loop.call_soon_threadsafe(done_ev.set) # raise sd.CallbackAbort if request_stream.empty(): if not zeros: zeros = b'\x00' * len(outdata) outdata[:] = zeros else: b = request_stream.get_nowait() # is get_nowait thread safe? if isinstance(b, StopAsyncIteration): raise sd.CallbackStop else: outdata[:] = b while request_stream.empty(): await asyncio.sleep(.1) self.mic_int = True async with self.i2s_lock: if volume is not None: # temporarily change volume pre_vol = self.speaker_volume() self.speaker_volume(volume) self._speaker_power(1) with sd.RawOutputStream(callback=cb, dtype=dtype, samplerate=samplerate, channels=1, blocksize=blocksize, finished_callback=fcb): await done_ev.wait() if volume is not None: self.speaker_volume(pre_vol)
def beforeRun(self): """ Start the sound device, and start to receive RTP packet from server """ self.out = sd.RawOutputStream(samplerate=self.fs, channels=2, dtype='float32', blocksize=1) self.out.start() self.setInterval(0) threading.Thread(target=self.recvRtp, daemon=True).start()
def server(self): """ Record a chunk with size ```frames_per_chunk``` and sends it through ```address``` and ```out_port``` """ stream = sd.RawOutputStream(samplerate=self.frames_per_second, channels=self.number_of_channels, dtype='int16') stream.start() with UdpReceiver(self.in_port) as receiver: while True: packed_chunk = receiver.receive(self.payload_size) chunk = self.unpack(packed_chunk) self.play(chunk, stream)
def __init__(self, duration_ms=20, sample_rate=48000.0, channel_count=2): self.duration_ms = duration_ms self.sample_rate = sample_rate self.sample_period_sec = 1.0 / self.sample_rate self.samples_per_frame = int( (duration_ms / 1000.0) / self.sample_period_sec) self.audio_stream = sd.RawOutputStream( samplerate=self.sample_rate, channels=channel_count, dtype='int16', blocksize=self.samples_per_frame) self.audio_stream.start()
def audio_thread() -> None: stream = sounddevice.RawOutputStream(self.samplerate, channels=self.nchannels, dtype=dtype) # type: ignore stream.start() thread_ready.set() try: while True: data = b"" repeat = False command = None try: command = self.command_queue.get(timeout=0.2) if command is None or command["action"] == "stop": break elif command["action"] == "play": sample = command["sample"] if params.auto_sample_pop_prevention: sample = sample.fadein( streaming.antipop_fadein).fadeout( streaming.antipop_fadeout) data = sample.view_frame_data() or b"" repeat = command["repeat"] except queue.Empty: self.all_played.set() data = b"" if data: stream.write(data) if self.playing_callback: sample = Sample.from_raw_frames( data, self.samplewidth, self.samplerate, self.nchannels) self.playing_callback(sample) if repeat: # remove all other samples from the queue and reschedule this one commands_to_keep = [] while True: try: c2 = self.command_queue.get(block=False) if c2["action"] == "play": continue commands_to_keep.append(c2) except queue.Empty: break for cmd in commands_to_keep: self.command_queue.put(cmd) if command: self.command_queue.put(command) finally: self.all_played.set() stream.stop() stream.close()
def callback(indata, frames, time, status): #print(frames) #print(time) if status: print(status) #print("Playing back ...") print("Processing. Please wait ...") with sd.RawOutputStream(samplerate=16000, channels=1, dtype='int16') as sdros: sdros.write(text_to_speech("Processing. Please wait ...")) text = speech_to_text(indata) print("You said:", text) sdros.write(text_to_speech("You said " + text)) print("Please say \"Smart Mirror\" to activate me.")
def play_sound(self): # sd.play(self.data, self.fs, device=sd.default.device) def callback_out(outdata, frames, time, status): assert frames == self.blocksize if status.output_underflow: print('Output underflow: increase blocksize?', file=sys.stderr) raise sd.CallbackAbort assert not status try: data = self.q.get_nowait() except queue.Empty: print('Buffer is empty: increase buffersize?', file=sys.stderr) raise sd.CallbackAbort if len(data) < len(outdata): outdata[:len(data)] = data outdata[len(data):] = b'\x00' * (len(outdata) - len(data)) raise sd.CallbackStop else: outdata[:] = data try: import soundfile as sf import sounddevice as sd import numpy assert numpy with sf.SoundFile("C:/Users/turch/PycharmProjects/Sonnic/source/Al.wav") as self.f: for _ in range(self.buffersize): data = self.f.buffer_read(self.blocksize, dtype='float32') if not data: break self.q.put_nowait(data) # Pre-fill queue stream = sd.RawOutputStream(device=sd.default.device, samplerate=self.f.samplerate, blocksize=self.blocksize, dtype='float32', channels=self.f.channels, callback=callback_out, finished_callback=self.event.set) print(self.f.channels) with stream: timeout = self.blocksize * self.buffersize / self.f.samplerate while data: data = self.f.buffer_read(self.blocksize, dtype='float32') self.q.put(data, timeout=timeout) self.event.wait() except sd.PortAudioError: print("Error opening file sound") except Exception as e: print(type(e).__name__ + ': ' + str(e))
def test_audio(self): if (self.is_test_audio_clicked == False): sd.default.samplerate = 44100 sd.default.latency = ['high', 'high'] sd.default.dtype = ['int24', 'int24'] sd.default.blocksize = socket_client_audio.READ_SIZE sd.default.channels = [ self.mic_dict['max_input_channels'], self.speaker_dict['max_output_channels'] ] sd.default.device = [self.input_device_id, self.output_device_id] try: self.audioin = sd.RawInputStream( #samplerate=int(self.mic_dict['default_samplerate']), ##blocksize=socket_client_audio.READ_SIZE, #device=self.input_device_id, #channels=self.mic_dict['max_input_channels'], #dtype=np.float32, #latency=self.mic_dict['default_low_input_latency'] ) audioin_flag = True except Exception as e: msgbx.showerror("Audio-in creation error", f'{e}') audioin_flag = False try: self.audioout = sd.RawOutputStream( #samplerate=int(self.speaker_dict['default_samplerate']), #blocksize=socket_client_audio.READ_SIZE, #device=self.output_device_id, #channels=self.speaker_dict['max_output_channels'], #dtype=np.float32, #latency=self.mic_dict['default_low_output_latency'] ) audioout_flag = True except Exception as e: msgbx.showerror("Audio-out creation error", f'{e}') audioout_flag = False if (audioin_flag and audioout_flag): self.is_test_audio_clicked = True thread_start_recording = Thread(target=self.record_audio) thread_start_recording.start() self.btn_audio_test.configure(text='Stop Audio Test') else: self.is_test_audio_clicked = False self.btn_audio_test.configure(text='Test Audio')
def __init__(self, base_freq=10, max_voices=10, amps=sine_amps): threading.Thread.__init__(self) self.stream = sounddevice.RawOutputStream(channels=1, samplerate=BIT_RATE) self.stream.start() self.alive = True self.base_freq = base_freq self.max_voices = max_voices self.ratios = [0] * max_voices self.phases = [0] * max_voices self.last_time = time() self.amps = amps / np.sum(amps) self.volumes = [1] * max_voices
def __init__(self, socket, key, read_chunk=None, block_chunk=0, audio_format=None, channels=None, rate=None): self._read_chunk = read_chunk; self._block_chunk = block_chunk; self._audio_format = audio_format; self._channels = channels; self._rate = rate; self._socket = socket; self._key = key; print(f"{RT.CYAN}Initializing Voice Streams{RT.RESET}"); self.playing_stream = sd.RawOutputStream(samplerate=self._rate, blocksize=self._block_chunk, channels=self._channels, dtype=self._audio_format); self.recording_stream = sd.RawInputStream(samplerate=self._rate, blocksize=self._block_chunk, channels=self._channels, dtype=self._audio_format); self.playing_stream.start(); self.recording_stream.start(); receive_thread = threading.Thread(target=self.receive_server_data).start(); print(f"{RT.CYAN}Voice Stream Active{RT.RESET}"); self.send_data_to_server();
def play_audio_file(fname=DETECT_DING): """Simple callback function to play a wave file. By default it plays a Ding sound. :param str fname: wave file name :return: None """ ding_wav = wave.open(fname, 'rb') ding_data = ding_wav.readframes(ding_wav.getnframes()) stream_out = sd.RawOutputStream(samplerate=ding_wav.getframerate(), channels=ding_wav.getnchannels(), dtype='int16') stream_out.start() stream_out.write(ding_data) time.sleep(0.2) stream_out.stop() stream_out.close()
def _playStart(self, filename): self.pq = queue.Queue(maxsize=self.buffersize) event = threading.Event() with sf.SoundFile(filename) as f: f.seek(0, sf.SEEK_END) self.total = f.tell() f.seek(0, sf.SEEK_SET) self.fplay = f self.status = 2 for _ in range(self.buffersize): data = f.buffer_read(self.blocksize, dtype='float32') if not data: break self.pq.put_nowait(data) # Pre-fill queue stream = sd.RawOutputStream( samplerate=f.samplerate, blocksize=self.blocksize, device=self.device, channels=f.channels, dtype='float32', callback=self.playCallback, finished_callback=event.set, extra_settings=self.extraOutputSettings) try: with stream: print("Start playing file", filename) timeout = self.blocksize * self.buffersize / f.samplerate * 8 while data and self.control == 2: data = f.buffer_read(self.blocksize, dtype='float32') self.pq.put(data, timeout=timeout) self.currentTime = f.tell() event.wait() # Wait until playback is finished print("Stop playing") except queue.Full: print("Timeout occured in playback") self.fplay = None self.status = 0 self.control = 0 for cb in self.callbacks: cb()
def play_wav_async(self, wav_file, buffersize=1024, blocksize=1024, socketio=None): q = queue.Queue(maxsize=buffersize) def callback(outdata, frames, time, status): assert frames == blocksize if status.output_underflow: print('Output underflow: increase blocksize?', file=sys.stderr) raise sd.CallbackAbort assert not status try: data = q.get_nowait() except queue.Empty: print('Buffer is empty: increase buffersize?', file=sys.stderr) raise sd.CallbackAbort if len(data) < len(outdata): outdata[:len(data)] = data outdata[len(data):] = b'\x00' * (len(outdata) - len(data)) raise sd.CallbackStop else: outdata[:] = data with sf.SoundFile(wav_file) as f: for _ in range(buffersize): data = f.buffer_read(blocksize, dtype='float32') if not data: break q.put_nowait(data) # Pre-fill queue stream = sd.RawOutputStream(samplerate=f.samplerate, blocksize=blocksize, channels=f.channels, dtype='float32', callback=callback, finished_callback=self._stopevent.set) with stream: timeout = blocksize * buffersize / f.samplerate while data and not self._stopevent.isSet(): data = f.buffer_read(blocksize, dtype='float32') q.put(data, timeout=timeout) self._stopevent.wait() # Wait until playback is finished return stream
def measure(vlatency): event = threading.Event() micdata = np.zeros(1) scdata = np.zeros(1) micstream = sd.InputStream( device=deviceMic, channels=argschannels, samplerate=argssamplerate, callback=mic_audio_callback) scstream = sd.InputStream( device=deviceSoundcard, channels=argschannels, samplerate=argssamplerate, callback=sc_audio_callback) with sf.SoundFile('sine440.wav') as f: for _ in range(argsbuffersize): data = f.buffer_read(argsblocksize, dtype='float32') if not data: break piq.put_nowait(data) # Pre-fill queue stream = sd.RawOutputStream( samplerate=f.samplerate, blocksize=argsblocksize, device=devicePi, channels=f.channels, dtype='float32', callback=pi_audio_callback, finished_callback=event.set) with stream: timeout = argsblocksize * argsbuffersize / f.samplerate with micstream: with scstream: while data: data = f.buffer_read(argsblocksize, dtype='float32') piq.put(data, timeout=timeout) micdata = np.append(micdata, micq.get()) scdata = np.append(scdata, scq.get()) while not event.is_set(): micdata = np.append(micdata, micq.get()) scdata = np.append(scdata, scq.get()) with open('micdata', 'wb') as micf: np.save(micf, micdata) with open('scdata', 'wb') as scf: np.save(scf, scdata) timediff, distance = findlag.measure(scdata, micdata, 44100, vlatency) with piq.mutex: piq.queue.clear() with scq.mutex: scq.queue.clear() with micq.mutex: micq.queue.clear() return timediff, distance
def send(q, Q, E): def callback(outdata, frames, time, status): assert frames == args.blocksize if status.output_underflow: print('Output underflow: increase blocksize?', file=sys.stderr) raise sd.CallbackAbort assert not status try: data = q.get_nowait() Q.put(np.frombuffer(data, dtype=np.float32)) except queue.Empty as e: print('Buffer is empty: increase buffersize?', file=sys.stderr) raise sd.CallbackAbort from e if len(data) < len(outdata): outdata[:len(data)] = data outdata[len(data):] = b'\x00' * (len(outdata) - len(data)) raise sd.CallbackStop else: outdata[:] = data try: with sf.SoundFile(args.filename) as f: for _ in range(args.buffersize): data = f.buffer_read(args.blocksize, dtype='float32') if not data: break q.put_nowait(data) # Pre-fill queue stream = sd.RawOutputStream( samplerate=f.samplerate, blocksize=args.blocksize, device=args.device, channels=f.channels, dtype='float32', callback=callback, finished_callback=E.set) with stream: timeout = args.blocksize * args.buffersize / f.samplerate while data: data = f.buffer_read(args.blocksize, dtype='float32') q.put(data, timeout=timeout) E.wait() except KeyboardInterrupt: parser.exit('\nInterrupted by user') except queue.Full: # A timeout occurred, i.e. there was an error in the callback parser.exit(1) except Exception as e: parser.exit(type(e).__name__ + ': ' + str(e))
def __init__(self, samplerate: int = 0, samplewidth: int = 0, nchannels: int = 0, frames_per_chunk: int = 0) -> None: super().__init__(samplerate, samplewidth, nchannels, frames_per_chunk, 0) self.initialize() dtype = self.samplewidth2dtype(self.samplewidth) self._empty_sound_data = b"\0" * self.chunksize self.mixed_chunks = self.mixer.chunks() self.stream = sounddevice.RawOutputStream( self.samplerate, channels=self.nchannels, dtype=dtype, # type: ignore blocksize=self.frames_per_chunk, callback=self.streamcallback) self.stream.start()