How to use the sounddevice.RawOutputStream function in sounddevice

To help you get started, we’ve selected a few sounddevice examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github BlackLight / platypush / platypush / plugins / sound / __init__.py View on Github external
next_t = min(t + blocktime, duration) \
                        if duration is not None else t + blocktime

                    data = mix.get_wave(t_start=t, t_end=next_t, samplerate=samplerate)
                    t = next_t

                    if duration is not None and t >= duration:
                        break

                q.put_nowait(data)  # Pre-fill the audio queue

            stream = self.active_streams[stream_index]
            completed_callback_event = self.completed_callback_events[stream_index]

            if stream is None:
                streamtype = sd.RawOutputStream if file else sd.OutputStream
                stream = streamtype(samplerate=samplerate, blocksize=blocksize,
                                    device=device, channels=channels,
                                    dtype='float32',
                                    callback=self._play_audio_callback(
                                        q=q, blocksize=blocksize,
                                        streamtype=streamtype,
                                        stream_index=stream_index),
                                    finished_callback=completed_callback_event.set)

                self._start_playback(stream_index=stream_index, stream=stream)

            with stream:
                # Timeout set until we expect all the buffered blocks to
                # be consumed
                timeout = blocksize * bufsize / samplerate
github spatialaudio / python-sounddevice / examples / play_long_file.py View on Github external
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=event.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)
            event.wait()  # Wait until playback is finished
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))
github spatialaudio / python-sounddevice / sounddevice.py View on Github external
A two-dimensional `numpy.ndarray` with one column per
            channel (i.e.  with a shape of ``(frames, channels)``) and
            with a data type specified by `dtype`.
        overflowed : bool
            ``True`` if input data was discarded by PortAudio after the
            previous call and before this call.

        """
        dtype, _ = _split(self._dtype)
        channels, _ = _split(self._channels)
        data, overflowed = RawInputStream.read(self, frames)
        data = _array(data, channels, dtype)
        return data, overflowed


class OutputStream(RawOutputStream):
    """Stream for output only.  See __init__() and Stream."""

    def __init__(self, samplerate=None, blocksize=None,
                 device=None, channels=None, dtype=None, latency=None,
                 extra_settings=None, callback=None, finished_callback=None,
                 clip_off=None, dither_off=None, never_drop_input=None,
                 prime_output_buffers_using_stream_callback=None):
        """PortAudio output stream (using NumPy).

        This has the same methods and attributes as `Stream`, except
        :meth:`~Stream.read` and `read_available`.
        Furthermore, the stream callback is expected to have a different
        signature (see below).

        Parameters
        ----------
github spatialaudio / python-sounddevice / sounddevice.py View on Github external
``True`` if additional output data was inserted after the
            previous call and before this call.

        """
        import numpy as np
        data = np.asarray(data)
        _, dtype = _split(self._dtype)
        _, channels = _split(self._channels)
        if data.ndim > 1 and data.shape[1] != channels:
            raise ValueError('Number of channels must match')
        if data.dtype != dtype:
            raise TypeError('dtype mismatch: {!r} vs {!r}'.format(
                data.dtype.name, dtype))
        if not data.flags.c_contiguous:
            raise TypeError('data must be C-contiguous')
        return RawOutputStream.write(self, data)
github BlackLight / platypush / platypush / plugins / sound / plugin.py View on Github external
data = mix.get_wave(t_start=t, t_end=next_t,
                                          samplerate=samplerate)
                    t = next_t

                    if duration is not None and t >= duration:
                        break

                q.put_nowait(data)  # Pre-fill the audio queue


            stream = self.active_streams[stream_index]
            completed_callback_event = self.completed_callback_events[stream_index]

            if stream is None:
                streamtype = sd.RawOutputStream if file else sd.OutputStream
                stream = streamtype(samplerate=samplerate, blocksize=blocksize,
                                    device=device, channels=channels,
                                    dtype='float32',
                                    callback=self._play_audio_callback(
                                        q=q, blocksize=blocksize,
                                        streamtype=streamtype,
                                        stream_index=stream_index),
                                    finished_callback=completed_callback_event.set)

                self._start_playback(stream_index=stream_index, stream=stream)

            with stream:
                # Timeout set until we expect all the buffered blocks to
                # be consumed
                timeout = blocksize * bufsize / samplerate
github BlackLight / platypush / platypush / plugins / sound / __init__.py View on Github external
def _play_audio_callback(self, q, blocksize, streamtype, stream_index):
        import sounddevice as sd

        is_raw_stream = streamtype == sd.RawOutputStream

        # noinspection PyUnusedLocal
        def audio_callback(outdata, frames, frame_time, status):
            if self._get_playback_state(stream_index) == PlaybackState.STOPPED:
                raise sd.CallbackStop

            while self._get_playback_state(stream_index) == PlaybackState.PAUSED:
                self.playback_paused_changed[stream_index].wait()

            if frames != blocksize:
                self.logger.warning('Received {} frames, expected blocksize is {}'.
                                    format(frames, blocksize))
                return

            if status.output_underflow:
                self.logger.warning('Output underflow: increase blocksize?')
github irmen / bouldercaves / bouldercaves / synthplayer / playback.py View on Github external
def audio_thread():
            mixed_chunks = self.mixer.chunks()
            stream = sounddevice.RawOutputStream(self.samplerate, channels=self.nchannels, dtype=dtype)
            stream.start()
            thread_ready.set()
            try:
                silence = b"\0" * self.chunksize
                while True:
                    data = next(mixed_chunks) or silence
                    stream.write(data)
                    if len(data) < self.chunksize:
                        stream.write(silence[len(data):])
                    if self.playing_callback:
                        sample = Sample.from_raw_frames(data, self.samplewidth, self.samplerate, self.nchannels)
                        self.playing_callback(sample)
            except StopIteration:
                pass
            finally:
                stream.stop()
github PetteriAimonen / esp-walkie-talkie / tools / listen.py View on Github external
import audioop
import time
import sounddevice
import numpy
import struct

stream = sounddevice.RawOutputStream(samplerate=12500, channels = 1, dtype='int16')

from socket import *
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('',18294))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.settimeout(1.0) 

s.sendto(b'', ('255.255.255.255', 18294))
send_t = time.time()

outfile = open('data', 'w')
outfile2 = open('data.bin', 'wb')

sine = numpy.round(numpy.sin(numpy.arange(0, numpy.pi*2*20, numpy.pi*2*20/1000)) * 0) # 16384)
sine_lin = b''
for i in range(len(sine)):
github irmen / bouldercaves / bouldercaves / synthplayer / playback.py View on Github external
def audio_thread():
            stream = sounddevice.RawOutputStream(self.samplerate, channels=self.nchannels, dtype=dtype)
            stream.start()
            thread_ready.set()
            try:
                while True:
                    data = b""
                    try:
                        command = self.command_queue.get(timeout=0.2)
                        if command is None or command["action"] == "stop":
                            break
                        elif command["action"] == "play":
                            data = command["sample"].view_frame_data() or b""
                    except queue.Empty:
                        self.all_played.set()
                        data = b""
                    if data:
                        stream.write(data)
github mkj / pru-mic / pdm / player.py View on Github external
def __init__(self, rate, chunk, streaming):
        self.stream = sounddevice.RawOutputStream(samplerate = int(rate), channels = 1,
            callback = self._callback, dtype='int16', blocksize=chunk)
        self.streaming = streaming
        if streaming:
            # short queue
            self.queue = queue.Queue(20)
        else:
            self.queue = queue.Queue(200)

        self.started = False