Exemplo n.º 1
0
 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()
Exemplo n.º 2
0
    def single_measurement(self, type=None):

        # little workaround of a problem with using ASIO from multiple threads
        # https://stackoverflow.com/questions/39858212/python-sounddevice-play-on-threads
        default_device = sd.query_devices(sd.default.device[0])
        default_api = sd.query_hostapis(default_device['hostapi'])
        if default_api['name'] == 'ASIO':
            sd._terminate()
            sd._initialize()

        self.recorded_sweep_l = []
        self.recorded_sweep_r = []
        self.feedback_loop = []

        if type is 'hpc':
            excitation = self.excitation_hpc
        else:
            excitation = self.excitation

        if not self.dummy_debugging:
            time.sleep(0.3)

        try:
            sd.check_input_settings(channels=self.num_input_channels_used)
            sd.check_output_settings(channels=self.num_output_channels_used)
        except:
            print(
                "Audio hardware error! Too many channels or unsupported samplerate"
            )
            return

        # do measurement
        recorded = sd.playrec(excitation,
                              channels=self.num_input_channels_used)
        sd.wait()

        # get the recorded signals
        if self.channel_layout_input[0] >= 0:
            self.recorded_sweep_l = recorded[:, self.channel_layout_input[0]]
        else:
            self.recorded_sweep_l = np.zeros(np.size(recorded, 0))

        if self.channel_layout_input[1] >= 0:
            self.recorded_sweep_r = recorded[:, self.channel_layout_input[1]]
        else:
            self.recorded_sweep_r = np.zeros(np.size(recorded, 0))

        if self.feedback_loop_used:
            self.feedback_loop = recorded[:, self.channel_layout_input[2]]
            if abs(self.feedback_loop.max()) < 0.0001:
                self.feedback_loop = np.random.random_sample(
                    self.feedback_loop.shape
                ) * 0.000001  # to avoid zero-division errors
        else:
            # if no FB loop, copy from original excitation sweep
            if type is 'hpc':
                self.feedback_loop = self.sweep_hpc_mono[:, 0]
            else:
                self.feedback_loop = self.sweep_mono[:, 0]
Exemplo n.º 3
0
 def is_output_format_supported(self, device, output_format):
     # raise sounddevice.PortAudioError if the format is not supported
     # the exception message contains the details, such as an invalid sample rate
     sounddevice.check_output_settings(
         device=device['index'],
         channels=device['max_output_channels'],
         dtype=output_format,
         samplerate=SAMPLING_RATE)
Exemplo n.º 4
0
    def __init__(self):
        try:
            sd.check_output_settings('wm8960')
        except ValueError:
            raise AIModuleFaultsException(
                "AI Speaker not found! Please contact our CS team.")

        for idx, device in enumerate(sd.query_devices()):
            if 'wm8960' in device:
                sd.default.device = idx
                break
Exemplo n.º 5
0
    def is_output_format_supported(self, device, output_format):
        try:
            sounddevice.check_output_settings(
                device=device['index'],
                channels=device['max_output_channels'],
                dtype=output_format,
                samplerate=SAMPLING_RATE)

            success = True
        except Exception as exception:
            Logger().push("Format is not supported: " + str(exception))
            success = False

        return success
Exemplo n.º 6
0
 def check_supported_sample_rate(self):
     import sounddevice as sd
     samplerates = 16000, 32000, 44100, 48000, 96000
     supported_samplerates = []
     for fs in samplerates:
         try:
             sd.check_output_settings(device=default.input_device_index, samplerate=fs)
         except Exception as e:
             #print(fs, e)
             pass
         else:
             supported_samplerates.append(fs)
     #print(supported_samplerates)
     return supported_samplerates
Exemplo n.º 7
0
    def is_output_format_supported(self, device, output_format):
        try:
            sounddevice.check_output_settings(
                device=device['index'],
                channels=device['max_output_channels'],
                dtype=output_format,
                samplerate=SAMPLING_RATE)

            success = True
        except Exception as exception:
            self.logger.push("Format is not supported: " + str(exception))
            success = False

        return success
Exemplo n.º 8
0
def test_soundcard(i="default",o="default", fs=fs, ch=2):

    dummy1sec = zeros(int(fs))

    print( 'Trying:' )
    print(f'    {sd.query_devices(i, kind="input" )["name"]}')
    print(f'    {sd.query_devices(o, kind="output")["name"]}')

    try:
        sd.default.device = i, o
    except Exception as e:
        print( f'(!) Error accesing devices [{i},{o}]: {e}' )
        return e

    try:
        chk_rec = sd.check_input_settings (i, channels=ch, samplerate=float(fs))
        chk_pb  = sd.check_output_settings(o, channels=ch, samplerate=float(fs))
        print( f'Sound card parameters OK' )
    except Exception as e:
        print( f'(!) Sound card [{i},{o}] ERROR: {e}' )
        return e

    try:
        dummy = sd.playrec(dummy1sec, samplerate=fs, channels=ch)
        print( 'Sound device settings are supported' )
    except Exception as e:
        print( f'(!) FAILED to playback and recording on selected device: {e}' )
        return e

    return 'ok'
Exemplo n.º 9
0
    def setup_audio_devices(self, sample_rate):
        input_devices = []
        output_devices = []
        for device in sd.query_devices():
            # Check if valid input
            try:
                sd.check_input_settings(device=device["name"],
                                        samplerate=sample_rate)
                input_devices.append(device["name"])
            except:
                pass

            # Check if valid output
            try:
                sd.check_output_settings(device=device["name"],
                                         samplerate=sample_rate)
                output_devices.append(device["name"])
            except Exception as e:
                # Log a warning only if the device is not an input
                if not device["name"] in input_devices:
                    warn(
                        "Unsupported output device %s for the sample rate: %d \nError: %s"
                        % (device["name"], sample_rate, str(e)))

        if len(input_devices) == 0:
            self.log("No audio input device detected. Recording may not work.")
            self.audio_in_devices_cb.addItems(["None"])
            self.audio_in_devices_cb.setDisabled(True)
        else:
            self.audio_in_devices_cb.clear()
            self.audio_in_devices_cb.addItems(input_devices)
            self.audio_in_devices_cb.currentTextChanged.connect(
                self.set_audio_device)

        if len(output_devices) == 0:
            self.log(
                "No supported output audio devices were found! Audio output may not work."
            )
            self.audio_out_devices_cb.addItems(["None"])
            self.audio_out_devices_cb.setDisabled(True)
        else:
            self.audio_out_devices_cb.clear()
            self.audio_out_devices_cb.addItems(output_devices)
            self.audio_out_devices_cb.currentTextChanged.connect(
                self.set_audio_device)

        self.set_audio_device()
Exemplo n.º 10
0
 def get_audio_output_device_supported_sample_rates(device,
                                                    channels,
                                                    dtype,
                                                    verbose=False):
     supported_samplerates = []
     for fs in (32000, 44100, 48000, 96000, 128000):
         try:
             sd.check_output_settings(device=device,
                                      samplerate=fs,
                                      channels=channels,
                                      dtype=dtype)
         except Exception as e:
             if verbose:
                 print(fs, e)
         else:
             supported_samplerates.append(fs)
     return supported_samplerates
Exemplo n.º 11
0
    def get_device(name='CABLE Input', kind='output', api=0):
        if isinstance(name, int):
            return name, sd.query_devices(name)

        devices = sd.query_devices()
        matching_devices = []
        for device_id in range(len(devices)):
            if name.lower() in devices[device_id].get('name').lower():
                try:
                    if kind == 'input':
                        sd.check_input_settings(device_id)
                    elif kind == 'output':
                        sd.check_output_settings(device_id)
                    else:
                        print('Invalid kind')
                        return None
                    matching_devices.append((device_id, devices[device_id]))
                except:
                    pass

        if not matching_devices:
            print("Unable to find device matching name", name, 'of kind', kind)
            return None

        found = False

        if isinstance(api, int):
            api = sd.query_hostapis(api).get('name')
        for device_id, device in matching_devices:
            if api in sd.query_hostapis(int(
                    device.get('hostapi'))).get('name'):
                found = True
                break

        if not found:
            print("Unable to find device matching host api", api,
                  'using first available...')
            return matching_devices[0]
        else:
            return device_id, device
Exemplo n.º 12
0
    def __init__(self, args):

        def audio_callback(indata, outdata, frames, time, status):
                '''Called by audio stream for each new buffer.'''
                indataQ.append(indata[::, LEFT])
                if self.out_enable:
                    outdata[:, LEFT] = self.out_sig
                else:
                    outdata.fill(0)
                self.cumulated_status |= status
                return None

        self.args = args
        self.out_enable = False

        sd.default.device = [args.input_dev, args.output_dev]
        sd.default.channels = 2
        sd.default.dtype = None
        sd.default.latency = None
        sd.default.samplerate = args.sample_rate
        sd.default.blocksize = args.buff_size
        sd.default.clip_off = True
        sd.default.dither_off = args.dither
        sd.default.never_drop_input = None
        sd.default.prime_output_buffers_using_stream_callback = None

        # Checks will throw errors for invalid settings.
        sd.check_input_settings()
        sd.check_output_settings()

        # Will store sounddevice status flags on buffer under/overflows, etc.
        self.cumulated_status = sd.CallbackFlags()
        # Will store data to write to output buffer.
        self.out_sig = None

        # Create the stream
        self.audio_stream = sd.Stream(callback=audio_callback)
Exemplo n.º 13
0
    def set_output_device(self, index):
        """Attempts to set the audio output device.

        Parameters
        ----------
        index : int
            The application's index of the output device

        Notes
        -----
            Emits the `output_device_changed_signal` with  the index of the current audio output device.

        """
        if index != self.get_current_output_device_index():
            device = self._output_devices[index]
            try:
                sound.check_output_settings(device=device['name'])
                sound.default.device[1] = device['name']
            except ValueError:
                self._logger.push("Output device not supported")

        print(self.get_current_output_device_index())

        self.output_device_changed_success_signal.emit(self.get_current_output_device_index())
 def driver_setter():
     if ms_win is not None:
         ms_win.destroy()
     if list_bx.curselection() == ():
         message_win(
             'Oi!', '''Select a device \n from the list or cancel
             ''')
         return
     num = list_bx.curselection()[0]
     num_name = sd.query_devices()[num].get('name')
     try:
         check_driver = sd.check_output_settings(
             device=num, channels=2, dtype='float32', samplerate=sample_rate)
         device_num.set(num)
         stream_restart(new_blocksize[0])
         message_win(
             'Driver Set', '''Device number {} ({}) \n set as output device.\n Blocksize = {}
             '''.format(num, num_name, new_blocksize))
     except sd.PortAudioError:
         message_win('sd.PortAudioError',
                     'Device number {} ({}) \n is not supported. Try another'.format(num, num_name))
Exemplo n.º 15
0
import sounddevice as sd

samplerates = 32000, 44100, 48000, 96000, 128000
device = 0

supported_samplerates = []
for fs in samplerates:
    try:
        sd.check_output_settings(device=device, samplerate=fs)
    except Exception as e:
        print(fs, e)
    else:
        supported_samplerates.append(fs)
print(supported_samplerates)
Exemplo n.º 16
0
parser.add_argument('-u', '--utc', action='store_true', help='set time in UTC')
args = parser.parse_args(remaining)

print('=' * 80)
print('')
print(
    '  DFC77-sync - a tool to synchronize DFC77 devices using sound speakers')
print('')
print('    For command line options use: dfc77-sync.py -h')
print('')
print('    Press Return to quit')
print('')
print('=' * 80)

try:
    sd.check_output_settings(args.device, samplerate=args.samplerate)
    samplerate = args.samplerate
except Exception:
    samplerate = sd.query_devices(args.device, 'output')['default_samplerate']

try:

    def callback(outdata, frames, time, status):
        if status:
            print(status, file=sys.stderr)

        global count_sec, count_dec, time_bits

        if count_sec < 59:
            if count_dec >= 2:
                outdata[:] = carrier[:]
Exemplo n.º 17
0
import _parseargs as parse
import utils as utils

# --- Parse command line arguments and check defaults
flag_defaultsInitialized = parse._checkdefaults()
args = parse._parse()
parse._defaults(args)
# -------------------------------

if flag_defaultsInitialized == True:

    if args.listdev == True:

        print(sd.query_devices())
        sd.check_input_settings()
        sd.check_output_settings()
        print("Default input and output device: ", sd.default.device)

    elif args.defaults == True:
        aa = np.load('_data/defaults.npy', allow_pickle=True).item()
        for i in aa:
            print(i + " => " + str(aa[i]))

    elif args.setdev == True:

        sd.default.device[0] = args.inputdevice
        sd.default.device[1] = args.outputdevice
        sd.check_input_settings()
        sd.check_output_settings()
        print(sd.query_devices())
        print("Default input and output device: ", sd.default.device)