Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
q.put(indata.copy())
try:
if args.samplerate is None:
device_info = sd.query_devices(args.device, 'input')
# soundfile expects an int, sounddevice provides a float:
args.samplerate = int(device_info['default_samplerate'])
if args.filename is None:
args.filename = tempfile.mktemp(prefix='delme_rec_unlimited_',
suffix='.wav', dir='')
# Make sure the file is opened before recording anything:
with sf.SoundFile(args.filename, mode='x', samplerate=args.samplerate,
channels=args.channels, subtype=args.subtype) as file:
with sd.InputStream(samplerate=args.samplerate, device=args.device,
channels=args.channels, callback=callback):
print('#' * 80)
print('press Ctrl+C to stop the recording')
print('#' * 80)
while True:
file.write(q.get())
except KeyboardInterrupt:
print('\nRecording finished: ' + repr(args.filename))
parser.exit(0)
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
event = asyncio.Event()
idx = 0
def callback(indata, frame_count, time_info, status):
nonlocal idx
if status:
print(status)
remainder = len(buffer) - idx
if remainder == 0:
loop.call_soon_threadsafe(event.set)
raise sd.CallbackStop
indata = indata[:remainder]
buffer[idx:idx + len(indata)] = indata
idx += len(indata)
stream = sd.InputStream(callback=callback, dtype=buffer.dtype,
channels=buffer.shape[1], **kwargs)
with stream:
await event.wait()
def streaming_thread():
try:
with sd.InputStream(samplerate=sample_rate, device=device,
channels=channels, callback=audio_callback,
dtype=dtype, latency=latency, blocksize=blocksize):
with open(fifo, 'wb') as audio_queue:
self.start_recording()
get_bus().post(SoundRecordingStartedEvent())
self.logger.info('Started recording from device [{}]'.format(device))
recording_started_time = time.time()
while self._get_recording_state() != RecordingState.STOPPED \
and (duration is None or
time.time() - recording_started_time < duration):
while self._get_recording_state() == RecordingState.PAUSED:
self.recording_paused_changed.wait()
get_args = {
'block': True,
def create_stream(self, device=None):
if self.stream is not None:
self.stream.close()
self.stream = sd.InputStream(
device=device, channels=1, callback=self.audio_callback)
self.stream.start()
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)
# Populate audio for live streaming
live_audio_feed.append(new_audio[:, 0].copy())
def callback(indata, frames, time, status):
if status:
text = ' ' + str(status) + ' '
print('\x1b[34;40m', text.center(args.columns, '#'),
'\x1b[0m', sep='')
if any(indata):
magnitude = np.abs(np.fft.rfft(indata[:, 0], n=fftsize))
magnitude *= args.gain / fftsize
line = (gradient[int(np.clip(x, 0, 1) * (len(gradient) - 1))]
for x in magnitude[low_bin:low_bin + args.columns])
print(*line, sep='', end='\x1b[0m\n')
else:
print('no input')
with sd.InputStream(device=args.device, channels=1, callback=callback,
blocksize=int(samplerate * args.block_duration / 1000),
samplerate=samplerate):
while True:
response = input()
if response in ('', 'q', 'Q'):
break
for ch in response:
if ch == '+':
args.gain *= 2
elif ch == '-':
args.gain /= 2
else:
print('\x1b[31;40m', usage_line.center(args.columns, '#'),
'\x1b[0m', sep='')
break
except KeyboardInterrupt:
async def inputstream_generator(channels=1, **kwargs):
"""Generator that yields blocks of input data as NumPy arrays."""
q_in = asyncio.Queue()
loop = asyncio.get_event_loop()
def callback(indata, frame_count, time_info, status):
loop.call_soon_threadsafe(q_in.put_nowait, (indata.copy(), status))
stream = sd.InputStream(callback=callback, channels=channels, **kwargs)
with stream:
while True:
indata, status = await q_in.get()
yield indata, status
def record(samplerate, channels, filename):
try:
q = queue.Queue()
def callback(indata, frames, time, status):
"""This is called (from a separate thread) for each audio block."""
if status:
print(status, file=sys.stderr)
q.put(indata.copy())
# Make sure the file is opened before recording anything:
with sf.SoundFile(filename, mode='x', samplerate=samplerate,
channels=channels) as file:
with sd.InputStream(samplerate=samplerate,
channels=channels, callback=callback):
print('Recording...')
print('press Ctrl+C to stop the recording')
while True:
file.write(q.get())
except KeyboardInterrupt:
print('\n Recording finished: ' + repr(filename))
return 0