How to use the sounddevice.PortAudioError 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 spatialaudio / python-sounddevice / sounddevice.py View on Github external
errormsg = _ffi.string(_lib.Pa_GetErrorText(err)).decode()
    if msg:
        errormsg = '{}: {}'.format(msg, errormsg)

    if err == _lib.paUnanticipatedHostError:
        # (gh82) We grab the host error info here rather than inside
        # PortAudioError since _check should only ever be called after a
        # failing API function call. This way we can avoid any potential issues
        # in scenarios where multiple APIs are being used simultaneously.
        info = _lib.Pa_GetLastHostErrorInfo()
        host_api = _lib.Pa_HostApiTypeIdToHostApiIndex(info.hostApiType)
        hosterror_text = _ffi.string(info.errorText).decode()
        hosterror_info = host_api, info.errorCode, hosterror_text
        raise PortAudioError(errormsg, err, hosterror_info)

    raise PortAudioError(errormsg, err)
github tlecomte / friture / friture / generator.py View on Github external
self.logger.info("Trying to write to output device '%s'", device['name'])

        # first see if the format is supported by PortAudio
        try:
            AudioBackend().is_output_format_supported(device, np.int16)
        except sounddevice.PortAudioError as err:
            self.on_device_change_error(previous_stream, previous_device, "Format is not supported: {0}".format(err))
            return

        try:
            self.stream = AudioBackend().open_output_stream(device, self.audio_callback)
            self.device = device
            self.stream.start()
            if self.state not in [STARTING, PLAYING]:
                self.stream.stop()
        except (sounddevice.PortAudioError, OSError) as err:
            self.on_device_change_error(previous_stream, previous_device, "Failed to open output device: {0}".format(err))
            return

        self.logger.info("Success")
        previous_stream.stop()

        self.settings_dialog.combobox_output_device.setCurrentIndex(AudioBackend().output_devices.index(self.device))
github spatialaudio / python-sounddevice / sounddevice.py View on Github external
self._callback = callback_ptr
        if userdata is None:
            userdata = _ffi.NULL
        self._ptr = _ffi.new('PaStream**')
        _check(_lib.Pa_OpenStream(self._ptr, iparameters, oparameters,
                                  samplerate, blocksize, stream_flags,
                                  callback_ptr, userdata),
               'Error opening {}'.format(self.__class__.__name__))

        # dereference PaStream** --> PaStream*
        self._ptr = self._ptr[0]

        self._blocksize = blocksize
        info = _lib.Pa_GetStreamInfo(self._ptr)
        if not info:
            raise PortAudioError('Could not obtain stream info')
        # TODO: assert info.structVersion == 1
        self._samplerate = info.sampleRate
        if not oparameters:
            self._latency = info.inputLatency
        elif not iparameters:
            self._latency = info.outputLatency
        else:
            self._latency = info.inputLatency, info.outputLatency

        if finished_callback:
            if isinstance(finished_callback, _ffi.CData):
                self._finished_callback = finished_callback
            else:

                def finished_callback_wrapper(_):
                    return finished_callback()
github spatialaudio / python-sounddevice / sounddevice.py View on Github external
0 Built-in Line Input, Core Audio (2 in, 0 out)
    > 1 Built-in Digital Input, Core Audio (2 in, 0 out)
    < 2 Built-in Output, Core Audio (0 in, 2 out)
      3 Built-in Line Output, Core Audio (0 in, 2 out)
      4 Built-in Digital Output, Core Audio (0 in, 2 out)

    """
    if kind not in ('input', 'output', None):
        raise ValueError('Invalid kind: {!r}'.format(kind))
    if device is None and kind is None:
        return DeviceList(query_devices(i)
                          for i in range(_check(_lib.Pa_GetDeviceCount())))
    device = _get_device_id(device, kind, raise_on_error=True)
    info = _lib.Pa_GetDeviceInfo(device)
    if not info:
        raise PortAudioError('Error querying device {}'.format(device))
    assert info.structVersion == 2
    name_bytes = _ffi.string(info.name)
    try:
        # We don't know beforehand if DirectSound and MME device names use
        # 'utf-8' or 'mbcs' encoding.  Let's try 'utf-8' first, because it more
        # likely raises an exception on 'mbcs' data than vice versa, see also
        # https://github.com/spatialaudio/python-sounddevice/issues/72.
        # All other host APIs use 'utf-8' anyway.
        name = name_bytes.decode('utf-8')
    except UnicodeDecodeError:
        if info.hostApi in (
                _lib.Pa_HostApiTypeIdToHostApiIndex(_lib.paDirectSound),
                _lib.Pa_HostApiTypeIdToHostApiIndex(_lib.paMME)):
            name = name_bytes.decode('mbcs')
        else:
            raise
github spatialaudio / python-sounddevice / sounddevice.py View on Github external
return err

    errormsg = _ffi.string(_lib.Pa_GetErrorText(err)).decode()
    if msg:
        errormsg = '{}: {}'.format(msg, errormsg)

    if err == _lib.paUnanticipatedHostError:
        # (gh82) We grab the host error info here rather than inside
        # PortAudioError since _check should only ever be called after a
        # failing API function call. This way we can avoid any potential issues
        # in scenarios where multiple APIs are being used simultaneously.
        info = _lib.Pa_GetLastHostErrorInfo()
        host_api = _lib.Pa_HostApiTypeIdToHostApiIndex(info.hostApiType)
        hosterror_text = _ffi.string(info.errorText).decode()
        hosterror_info = host_api, info.errorCode, hosterror_text
        raise PortAudioError(errormsg, err, hosterror_info)

    raise PortAudioError(errormsg, err)
github tlecomte / friture / friture / audiobackend.py View on Github external
def get_stream_time(self):
        if self.stream is None:
            return 0

        try:
            return self.stream.time
        except (sounddevice.PortAudioError, OSError):
            if self.stream.device not in self.devices_with_timing_errors:
                self.devices_with_timing_errors.append(self.stream.device)
                self.logger.exception("Failed to read stream time")
            return 0
github spatialaudio / python-sounddevice / sounddevice.py View on Github external
callback (see the *callback* argument of `Stream`).
        The time values are monotonically increasing and have
        unspecified origin.

        This provides valid time values for the entire life of the
        stream, from when the stream is opened until it is closed.
        Starting and stopping the stream does not affect the passage of
        time as provided here.

        This time may be used for synchronizing other events to the
        audio stream, for example synchronizing audio to MIDI.

        """
        time = _lib.Pa_GetStreamTime(self._ptr)
        if not time:
            raise PortAudioError('Error getting stream time')
        return time
github spatialaudio / python-sounddevice / examples / rec_gui.py View on Github external
for idx in hostapi['devices']
                if sd.query_devices(idx)['max_output_channels'] > 0]
            device_list['values'] = [
                sd.query_devices(idx)['name'] for idx in device_ids]
            default = hostapi['default_output_device']
            if default >= 0:
                device_list.current(device_ids.index(default))
                device_list.event_generate('<>')

        def select_device(*args):
            self.result = device_ids[device_list.current()]

        hostapi_list.bind('<>', update_device_list)
        device_list.bind('<>', select_device)

        with contextlib.suppress(sd.PortAudioError):
            hostapi_list.current(sd.default.hostapi)
            hostapi_list.event_generate('<>')
github ericgibert / supersid / supersid / sampler.py View on Github external
def capture_1sec(self):
            # duration = 1 sec hence   1 x self.audio_sampling_rate = self.audio_sampling_rate
            one_sec_record = b''
            try:
                one_sec_record = sounddevice.rec(self.audio_sampling_rate)
            except sounddevice.PortAudioError as err:
                print("Error reading device", self.name)
                print(err)
            return one_sec_record[0]