Skip to content

Instantly share code, notes, and snippets.

@mathiassmichno
Created April 24, 2017 21:47
Show Gist options
  • Save mathiassmichno/4906e67a7aac16a120cb8ce7510b3bbf to your computer and use it in GitHub Desktop.
Save mathiassmichno/4906e67a7aac16a120cb8ce7510b3bbf to your computer and use it in GitHub Desktop.
import sounddevice as sd
import numpy as np
from pprint import pprint
import matplotlib.pyplot as plt
import time
import scipy.io.wavfile as wav
from time import time as t
sd._initialize()
class Snd(object):
def __init__(self, dev_in_name=None, dev_out_name=None, dev_name=None):
assert dev_name or ( dev_in_name and dev_out_name)
super().__init__()
self.dev_in = sd.query_devices(dev_in_name if dev_in_name else dev_name, 'input')
self.dev_out = sd.query_devices(dev_out_name if dev_out_name else dev_name, 'output')
self.dev_in['name'] = dev_in_name
self.dev_out['name'] = dev_out_name
self.in_stream = None
self.out_stream = None
self.dtype = 'int16'
def rec(self, duration, samplerate=None, channels=None):
assert duration
if not channels:
channels = self.dev_in['max_input_channels']
if not samplerate:
samplerate = int(self.dev_in['default_samplerate'])
self._recorded_frames = 0
self.in_data = np.zeros((duration * samplerate, channels))
def _in_callback(indata, frames, time, status):
if status:
print(status)
if self._recorded_frames + frames >= duration * samplerate:
frames = (duration * samplerate) - self._recorded_frames
self.in_data[self._recorded_frames:self._recorded_frames + frames] = indata[0:frames]
self._recorded_frames += frames
if self._recorded_frames >= duration * samplerate:
raise sd.CallbackStop()
self.in_stream = sd.InputStream(samplerate=samplerate, channels=channels,
device=self.dev_in['name'], callback=_in_callback)
self.in_stream.start()
a = Snd(dev_name='HyperX WASAPI')
b = Snd(dev_in_name='LineIn WASAPI', dev_out_name='M-3 WASAPI')
pprint(a)
pprint(a.dev_in)
pprint(a.dev_out)
pprint(b)
pprint(b.dev_in)
pprint(b.dev_out)
a.rec(5)
b.rec(5)
while b.in_stream.active or a.in_stream.active:
time.sleep(1)
for channel in a.in_data.T:
plt.plot(channel)
plt.show()
for channel in b.in_data.T:
plt.plot(channel)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment