How to use the sounddevice.default.channels 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-rtmixer / examples / bleeperoo.py View on Github external
start_min = 0
start_max = 10
channels = None

if duration_min < max(attack, release):
    raise ValueError('minimum duration is too short')

fade_in = np.linspace(0, 1, num=int(samplerate * attack))
fade_out = np.linspace(1, 0, num=int(samplerate * release))

r = np.random.RandomState(seed)

bleeplist = []

if channels is None:
    channels = sd.default.channels['output']
    if channels is None:
        channels = sd.query_devices(device, 'output')['max_output_channels']

for _ in range(bleeps):
    duration = r.uniform(duration_min, duration_max)
    amplitude = r.uniform(amplitude_min, amplitude_max)
    pitch = r.uniform(pitch_min, pitch_max)
    # Convert MIDI pitch (https://en.wikipedia.org/wiki/MIDI_Tuning_Standard)
    frequency = 2 ** ((pitch - 69) / 12) * 440
    t = np.arange(int(samplerate * duration)) / samplerate
    bleep = amplitude * np.sin(2 * np.pi * frequency * t, dtype='float32')
    bleep[:len(fade_in)] *= fade_in
    bleep[-len(fade_out):] *= fade_out

    # Note: Arrays must be 32-bit float and C contiguous!
    assert bleep.dtype == 'float32'
github unique1o1 / Meta-Music / Metamusic / recognize.py View on Github external
def __init__(self, dejavu):
        super(MicrophoneRecognizer, self).__init__(dejavu)
        sd.default.samplerate = MicrophoneRecognizer.default_samplerate
        sd.default.channels = MicrophoneRecognizer.default_channels
        sd.default.dtype = MicrophoneRecognizer.default_format
        self.data = [[], []]
        self.recorded = False
github qobi / ece57000 / speech_classifier_gui.py View on Github external
from gui import *
from distances import *
from nearest_neighbor_classifier import *
import sounddevice as sd
import numpy as np
import time

sd.default.samplerate = 8000
sd.default.channels = 1
points = []
labels = []

distance = dtw(L2_vector(L2_scalar))

def start_recording(maximum_duration, for_classify):
    def internal():
        if (not for_classify) or len(points)>0:
            global waveform, start_time
            message("")
            waveform = sd.rec(maximum_duration*sd.default.samplerate)
            start_time = time.time()
    return internal

def stop_recording():
    global waveform
github LCAV / pyroomacoustics / pyroomacoustics / experimental / delay_calibration.py View on Github external
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.')
github LCAV / FRIDA / experiment / play_sweeps.py View on Github external
if __name__ == "__main__":

    from realtimeaudio import AudioGetter

    # Signal parameters
    fs = 48000.
    T = 3.
    T_sweep = 0.96*T
    T_sleep = 1.
    
    # Setup device
    sd.default.device = 2
    sd.default.samplerate = fs
    sd.default.channels = (8,1)

    # create sweep signal
    sweep = np.zeros(int(T*fs))

    # save the sweep to deconvolve later
    short_sweep = sine_sweep(T_sweep, fs, f_low=20., f_high=fs/2-100.)
    win_sweep = window(short_sweep, int(fs*0.01))
    sweep[:int(T_sweep*fs)] = win_sweep
    wavfile.write("short_sweep.wav", fs, short_sweep)
    wavfile.write("win_sweep.wav", fs, win_sweep)

    # Create multichannel signal
    signal = np.zeros((sd.default.channels[0]*sweep.shape[0], sd.default.channels[0]))

    compactsix_server = AudioGetter("192.168.2.11:8888", sd.default.channels[0]*T+1, fs=fs, channels=6)
    compactsix_server.start()
github spatialaudio / python-sounddevice / sounddevice.py View on Github external
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:
        # If NumPy is available, get canonical dtype name
        dtype = _sys.modules['numpy'].dtype(dtype).name
github LCAV / FRIDA / experiment / play_sweeps.py View on Github external
# save the sweep to deconvolve later
    short_sweep = sine_sweep(T_sweep, fs, f_low=20., f_high=fs/2-100.)
    win_sweep = window(short_sweep, int(fs*0.01))
    sweep[:int(T_sweep*fs)] = win_sweep
    wavfile.write("short_sweep.wav", fs, short_sweep)
    wavfile.write("win_sweep.wav", fs, win_sweep)

    # Create multichannel signal
    signal = np.zeros((sd.default.channels[0]*sweep.shape[0], sd.default.channels[0]))

    compactsix_server = AudioGetter("192.168.2.11:8888", sd.default.channels[0]*T+1, fs=fs, channels=6)
    compactsix_server.start()

    # Play the sweep on each channel
    for ch in range(sd.default.channels[0]):
        s = ch*sweep.shape[0]
        e = (ch+1)*sweep.shape[0]

        signal[s:e,ch] = sweep


    data_in = sd.playrec(signal, fs, blocking=True)

    compactsix_server.join()
github LCAV / FRIDA / experiment / play_speech.py View on Github external
file_counter = 1

# start the compactsix array recorder
compactsix_server = AudioGetter("192.168.2.11:8888", chunk_length+5, fs=fs_in, channels=6)
compactsix_server.start()

# here is a skip counter for when the experiments fail midway but we don't
# want to redo everything
skip = 0
skip_counter = 0

print 'Don''t forget, we''ll be skipping the first {} signals'.format(skip)

# Play the speech  on each channel
s1 = signals[0]
for ch in range(sd.default.channels[1]):

    if skip_counter < skip:
        skip_counter += 1
        continue

    signal[:s1.shape[0],ch] = s1
    sd.play(signal, fs_out, blocking=True)
    signal[:,ch] = 0.
    time.sleep(T_sleep)

    time_counter += length/fs_out + T_sleep
    if time_counter > chunk_length:
        # wait for the file from the remote array
        compactsix_server.join()
        # and save it
        wavfile.write(
github LCAV / pyroomacoustics / pyroomacoustics / experimental / delay_calibration.py View on Github external
distance : float, optional
            Distance between the speaker and microphone
        ch_in : int, optional
            The input channel to use. If not specified, all channels are calibrated
        ch_out : int, optional
            The output channel to use. If not specified, all channels are calibrated
        '''

        if ch_out is None:
            ch_out = [0]

        # create the maximum length sequence
        mls = 0.95*np.array(2*signal.max_len_seq(self.mls_bits)[0] - 1, dtype=np.float32)

        # output signal
        s = np.zeros((mls.shape[0] + int(self.pad_time*self.fs), sd.default.channels[1]), dtype=np.float32)

        # placeholder for delays
        delays = np.zeros((sd.default.channels[0], len(ch_out)))

        try:
            import matplotlib.pyplot as plt
        except ImportError:
            import warnings
            warnings.warn('Matplotlib is required for plotting')
            return

        for och in ch_out:
            # play and record the signal simultaneously
            s[:mls.shape[0], och] = 0.1 * mls
            rec_sig = sd.playrec(s, self.fs, channels=sd.default.channels[0], blocking=True)
            s[:,och] = 0
github qobi / ece57000 / speech_classifier.py View on Github external
from gui import *
from distances_and_classifiers import *
import sounddevice as sd
import numpy as np
import time

sd.default.samplerate = 8000
sd.default.channels = 1
points = []
labels = []

def start_recording(maximum_duration):
    def internal():
        global waveform, start_time
        message("")
        waveform = sd.rec(maximum_duration*sd.default.samplerate)
        start_time = time.time()
    return internal

def stop_recording():
    global waveform
    actual_time = time.time()-start_time
    sd.stop()
    samples = min(int(actual_time*sd.default.samplerate), len(waveform))