Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _get_device_id(id_or_query_string, kind, raise_on_error=False):
"""Return device ID given space-separated substrings."""
assert kind in ('input', 'output', None)
if id_or_query_string is None:
id_or_query_string = default.device
idev, odev = _split(id_or_query_string)
if kind == 'input':
id_or_query_string = idev
elif kind == 'output':
id_or_query_string = odev
else:
if idev == odev:
id_or_query_string = idev
else:
raise ValueError('Input and output device are different: {!r}'
.format(id_or_query_string))
if isinstance(id_or_query_string, int):
return id_or_query_string
device_list = []
def set_default_devices(input_device, output_device):
"""Sets sounddevice default devices
Args:
input_device: Input device object
output_device: Output device object
Returns:
- Input device name and host API as string
- Output device name and host API as string
"""
host_api_names = get_host_api_names()
input_device_str = f'{input_device["name"]} {host_api_names[input_device["hostapi"]]}'
output_device_str = f'{output_device["name"]} {host_api_names[output_device["hostapi"]]}'
sd.default.device = (input_device_str, output_device_str)
return input_device_str, output_device_str
def __repr__(self):
idev = _get_device_id(default.device['input'], 'input')
odev = _get_device_id(default.device['output'], 'output')
digits = len(str(_lib.Pa_GetDeviceCount() - 1))
hostapi_names = [hostapi['name'] for hostapi in query_hostapis()]
text = '\n'.join(
u'{mark} {idx:{dig}} {name}, {ha} ({ins} in, {outs} out)'.format(
mark=(' ', '>', '<', '*')[(idx == idev) + 2 * (idx == odev)],
idx=idx,
dig=digits,
name=info['name'],
ha=hostapi_names[info['hostapi']],
ins=info['max_input_channels'],
outs=info['max_output_channels'])
for idx, info in enumerate(self))
return text
now = time.strftime("%Y%m%d-%H%M%S")
recording_folder = './Recordings/'
recording_filename = now + '-compactsix-speech-{}.wav'
sample_folder = './samples/'
samples = [ 'fq_sample{}.wav'.format(i) for i in range(3) ]
# the list contains tuples of (fs, signal)
fs_out, s = wavfile.read(sample_folder + samples[0]) # just to get the sampling rate
signals = [wavfile.read(sample_folder + sample)[1] for sample in samples]
# the microphones have high sampling rate
fs_in = 48000
# Setup output device
sd.default.device = 2
sd.default.samplerate = fs_out
sd.default.channels = 8
# time between two samples
T_sleep = 0.2
# We record in chunks because of limitations of pyramic array
chunk_length = 70
# Normalize the amplitude and length of speech signals
length = np.max([s.shape[0] for s in signals])
max_amp = np.max([np.max(np.abs(s)) for s in signals])
for s in signals:
s *= 0.95 / max_amp
def get_default_input_device(self):
try:
index = sounddevice.default.device[0]
except IOError:
index = None
return index
os.environ['THEANO_FLAGS'] = THEANO_FLAGS
os.environ['KERAS_BACKEND'] = 'theano'
import keras
keras.backend.set_image_dim_ordering('th')
with open('ears/model.json', 'r') as file:
cfg = file.read()
model = keras.models.model_from_json(cfg)
model.load_weights('ears/model.h5')
logger.debug('Loaded Keras model with weights.')
# Start audio capture
sd.default.device = AUDIO_DEVICE
logger.info('Priming recording device {}.'.format(AUDIO_DEVICE))
stream = sd.InputStream(channels=1, dtype='float32', callback=capture_audio,
samplerate=SAMPLING_RATE, blocksize=BLOCK_SIZE)
stream.start()
blocks = []
processing_queue = collections.deque()
# Process incoming audio blocks
while True:
while len(audio_queue) > 0 and len(blocks) < PREDICTION_STEP:
blocks.append(audio_queue.popleft())
if len(blocks) == PREDICTION_STEP:
new_audio = np.concatenate(blocks)
def _get_stream_parameters(kind, device, channels, dtype, latency,
extra_settings, samplerate):
"""Get parameters for one direction (input or output) of a stream."""
assert kind in ('input', 'output')
if device is None:
device = default.device[kind]
if channels is None:
channels = default.channels[kind]
if dtype is None:
dtype = default.dtype[kind]
if latency is None:
latency = default.latency[kind]
if extra_settings is None:
extra_settings = default.extra_settings[kind]
if samplerate is None:
samplerate = default.samplerate
device = _get_device_id(device, kind, raise_on_error=True)
info = query_devices(device)
if channels is None:
channels = info['max_' + kind + '_channels']
try:
# adjust the amplitude
sweep *= volume
# zero pad as needed
pre_zeros = int(pre_delay * fs)
post_zeros = int(post_delay * fs)
test_signal = np.concatenate(
(np.zeros(pre_zeros), sweep, np.zeros(post_zeros)) )
# setup audio interface parameters
if channels_input_mapping is None:
channels_input_mapping = [1]
if channels_output_mapping is None:
channels_output_mapping = [1]
if dev_in is not None:
sd.default.device[0] = dev_in
if dev_out is not None:
sd.default.device[1] = dev_out
# repeat if we need to play in multiple channels
if len(channels_output_mapping) > 1:
play_signal = np.tile(test_signal[:, np.newaxis],
(1, len(channels_output_mapping)))
else:
play_signal = test_signal
recorded_signal = sd.playrec(
test_signal, samplerate=fs,
input_mapping=channels_input_mapping,
output_mapping=channels_output_mapping,
blocking=True
)
input_device: Input device name. System default is used if not given.
output_device: Output device name. System default is used if not given.
host_api: Host API name
min_channels: Minimum number of output channels that the output device needs to support
Returns:
- Input device object
- Output device object
"""
# Find devices
devices = sd.query_devices()
# Select input device
if input_device is None:
# Not given, use default
input_device = devices[sd.default.device[0]]['name']
input_device = get_device(input_device, 'input', host_api=host_api)
# Select output device
if output_device is None:
# Not given, use default
output_device = devices[sd.default.device[1]]['name']
output_device = get_device(output_device, 'output', host_api=host_api, min_channels=min_channels)
return input_device, output_device
delays[ich,och] = np.argmax(xcorr)
plt.plot(xcorr)
plt.show()
# subtract distance
delays -= int(distance / self.c * self.fs)
return delays
if __name__ == "__main__":
try:
import sounddevice as sd
sd.default.device = (2,2)
sd.default.channels = (1,2)
dc = DelayCalibration(48000, mls_bits=16, pad_time=0.5, repeat=1, temperature=25.6, humidity=30.)
delays = dc.run(ch_out=[0,1])
print(delays)
except:
raise ImportError('Sounddevice package must be installed to run that script.')