Пример #1
0
def loopback_microphone():
    if sys.platform == 'win32':
        # must install https://www.vb-audio.com/Cable/index.htm
        return soundcard.get_microphone('Cable')
    elif sys.platform == 'darwin':
        # must install soundflower
        return soundcard.get_microphone('Soundflower64')
    elif sys.platform == 'linux':
        return soundcard.get_microphone('Null', include_loopback=True)
    else:
        raise RuntimeError('Unknown platform {}'.format(sys.platform))
Пример #2
0
def loopback_microphone():
    if sys.platform == 'win32':
        # must install https://www.vb-audio.com/Cable/index.htm
        return soundcard.get_microphone('Cable')
    elif sys.platform == 'darwin':
        # must install soundflower
        return soundcard.get_microphone('Soundflower64')
    elif sys.platform == 'linux':
        return soundcard.get_microphone('Null', exclude_monitors=False)
    else:
        raise RuntimeError(f'Unknown platform {sys.platform}')
Пример #3
0
    def get_devices(self) -> None:
        """
        Updates input_devices and output_devices
        """
        self.input_devices = []
        for s in self.gui.win_vars.input_sound:
            if s.name == gui_main.DEFAULT_SOUND_NAME:
                continue
            self.input_devices.append(sc.get_microphone(id=s.name, include_loopback=True))

        self.output_devices = []
        for s in self.gui.win_vars.output_sound:
            if s.name == gui_main.DEFAULT_SOUND_NAME:
                continue
            self.output_devices.append(sc.get_microphone(id=s.name, include_loopback=True))
Пример #4
0
    def start(self):
        import soundcard as sc
        try:
            sc.set_name('Panon')
        except (AttributeError, NotImplementedError):
            pass

        if self.device_id == 'all':
            mics = sc.all_microphones(exclude_monitors=False)
        elif self.device_id == 'allspeakers':
            mics = [
                mic for mic in sc.all_microphones(exclude_monitors=False)
                if mic.id.endswith('.monitor')
            ]
        elif self.device_id == 'default':
            mics = [sc.default_microphone()]
        else:
            mics = [
                sc.get_microphone(
                    self.device_id,
                    include_loopback=False,
                    exclude_monitors=False,
                )
            ]
        self.streams = []
        for mic in mics:
            stream = mic.recorder(
                self.sample_rate,
                self.channel_count,
                self.blocksize,
            )
            stream.__enter__()
            self.streams.append(stream)
Пример #5
0
def start_recording(recorded_queue, ms):
    audio_array = sc.get_microphone(
        const.SOUNDCARD_ID, include_loopback=True).record(
            numframes=int(const.FRAMERATE * ms / 1000),
            samplerate=int(const.FRAMERATE))

    recorded_queue.put((audio_array, time.time()))
    recorded_queue.close()
    return
Пример #6
0
    def __init__(self,
                 ctx,
                 samplerate=44100,
                 buffersize=1024,
                 device_in=0,
                 channel_in=0,
                 device_out=0,
                 channel_out=0,
                 volume=1.0):
        self.ctx = ctx
        self.samplerate = samplerate
        self.buffersize = buffersize
        self.volume = volume

        # Select audio devices and its channels
        inputs = all_inputs()
        outputs = all_outputs()

        if len(inputs) - 1 < device_in:
            raise IndexError(
                'No input device with index {} given'.format(device_in))

        if len(outputs) - 1 < device_out:
            raise IndexError(
                'No output device with index {} given'.format(device_out))

        self._input = sc.get_microphone(inputs[device_in].id)
        self._output = sc.get_speaker(outputs[device_out].id)

        if self._input.channels - 1 < channel_in:
            raise IndexError(
                'No input channel with index {} given'.format(channel_in))

        if self._output.channels - 1 < channel_out:
            raise IndexError(
                'No output channel with index {} given'.format(channel_out))

        ctx.log('Input device "{}" @ channel {}'.format(
            self._input.name, channel_in))
        ctx.log('Output device "{}" @ channel {}'.format(
            self._output.name, channel_out))

        self._input_ch = channel_in
        self._output_ch = channel_out

        # Prepare reading thread
        self._lock = threading.Lock()
        self._frames = np.array([])
        self.is_running = False

        # Prepare writing thread
        self._buffer = np.array([])
Пример #7
0
    def create_threads(self) -> None:
        """
        Creates the audio threads. This is called when Update is pushed.
        """
        self.threads = [[None] * len(self.gui.win_vars.output_sound)] * len(self.gui.win_vars.input_sound)

        for x, i in enumerate(self.gui.win_vars.input_sound):
            for y, o in enumerate(self.gui.win_vars.output_sound):
                if i.name == gui_main.DEFAULT_SOUND_NAME or o.name == gui_main.DEFAULT_SOUND_NAME:
                    continue

                self.threads[x][y] = threading.Thread(target=self.output_thread,
                                                      args=(self.run_id,
                                                            sc.get_microphone(i.name, True), lambda: i.volume,
                                                            sc.get_speaker(o.name), lambda: o.volume))
                self.threads[x][y].start()
Пример #8
0
    def __init__(self, rate=44100, period=1024, *args, **kwargs):
        threading.Thread.__init__(self)
        self.daemon = True
        self._s_lock = threading.Lock()

        Sampler.__init__(self, rate, period, *args, **kwargs)

        # Query for which card/device to use
        selections = sc.all_microphones(include_loopback=True)
        for i, s in enumerate(selections):
            print("{}: {}".format(i, s))

        dev = int(input("Please enter the number of the device to use: "))
        dev_name = selections[dev].name

        # Instantiate our Soundcard mixin
        self._mixin = sc.get_microphone(id=dev_name, include_loopback=True)
Пример #9
0
def start_sequence(**kwargs):
    """
    Main sequence
    """

    dmx = BuildDMX(pixels=kwargs['pixels'],
                   fps=kwargs['fps'],
                   brightness=kwargs['brightness'],
                   multi=kwargs['multi'],
                   rr=kwargs['rr'],
                   rl=kwargs['rl'],
                   ip=kwargs['ip'])
    previous_dmx: dict = {}
    recording_device = sc.get_microphone(kwargs['deviceid'],
                                         include_loopback=True)
    sender = sacn.sACNsender()
    try:
        i = 0
        while True:
            data = recording_device.record(samplerate=kwargs['sampleRate'],
                                           numframes=kwargs['defaultframes'],
                                           blocksize=256)
            if data is not None:
                (dmx_data, previous_dmx) = dmx.output(data, previous_dmx)
                if not sender.get_active_outputs():
                    if any(map(lambda ele: ele != 0, dmx_data)):
                        sender.activate_output(1)
                        sender[1].destination = kwargs['ip']
                        sender.start()
                else:
                    sender[1].dmx_data = dmx_data
                    if not any(map(lambda ele: ele != 0, dmx_data)):
                        # Don't deactivate too quickly. Wait a few seconds.
                        if i >= 500:
                            sender.deactivate_output(1)
                            sender.stop()
                            i = 0
                        i += 1
                terminal_led(dmx_data)
            time.sleep(0.01)
    except KeyboardInterrupt:
        sender.stop()
        cursor.show()
Пример #10
0
    def __init__(self, id: int or str = None,
                 samplerate: int = config.samplerate,
                 blocksize: int = config.blocksize,
                 channels: List[int] = config.channels['in'],
                 buffersize: int = config.buffersize,
                 dtype: _np.dtype = config.dtype,
                 loopback: bool = False):
        """
        Record audio from input device directly into shared memory.



        Parameters
        ----------
        id : int or str, optional
            DESCRIPTION. The default is None.
        samplerate : int, optional
            DESCRIPTION. The default is config.samplerate.
        blocksize : int, optional
            DESCRIPTION. The default is config.blocksize.
        channels : List[int], optional
            DESCRIPTION. The default is config.channels.
        buffersize : int, optional
            DESCRIPTION. The default is config.buffersize.
        dtype : _np.dtype, optional
            DESCRIPTION. The default is config.dtype.
        loopback : bool, optional
            DESCRIPTION. The default is False.

        Returns
        -------
        None.

        """
        _Streamer.__init__(self, samplerate, blocksize, channels, buffersize, dtype)
        self._channels = channels
        self._mic = _sc.default_microphone() if not id \
            else _sc.get_microphone(id, include_loopback=loopback)
        return
Пример #11
0
 def _process(self):
     mic=soundcard.get_microphone(self.input_device_index or self.input_device_name)
     with mic.recorder(samplerate=self.RATE, blocksize=self.frames_per_buffer, channels=self.CHANNELS) as recorder:
         while not self.done:    
             if not self.stopped and not self.done:
                 try:
                     data=recorder.record(self.frames_per_buffer)
                 except Exception as ex:
                     self.print_message( "error: {0}".format(str(ex)))
                     self.done=True
                 if len(data)==0:
                     self.print_message("no data")
                     self.done=True
                 else:
                     data=data.astype("float32").tobytes()
 
             if (not self.stopped and 
                 not self.done and
                 data is not None):  
                 self.send_output(data)
             
         self.send_output(None)
     self.stopped=True
Пример #12
0
    def __init__(self,
                 rate=16000,
                 frames_size=1280,
                 channels=1,
                 device_name='default',
                 bits_per_sample=16):
        super(Source, self).__init__()
        self.logger = logging.getLogger(self.__class__.__name__)

        self.mic = None
        self.rate = rate
        self.channels = channels
        self.done = False
        self.count = 0
        self.frames_size = frames_size

        if device_name:
            try:
                self.mic = sc.get_microphone(device_name)
            except Exception:
                self.logger.warn("can't get by device_name")
                self.mic = sc.default_microphone()
        else:
            self.mic = sc.default_microphone()
Пример #13
0
# get the current default speaker on your system:
default_speaker = sc.default_speaker()
print(f"\nDefault speaker is: {default_speaker}\n")

# get a list of all microphones:
mics = sc.all_microphones()
print("Microphones:")
for m in mics:
    print(m)
# get the current default microphone on your system:
default_mic = sc.default_microphone()
print(f"\nDefault mic is: {default_mic}\n")

# search for a sound card by substring:
one_speaker = sc.get_speaker("Mono")
one_mic = sc.get_microphone("Mono")
# fuzzy-search to get the same results:
# one_speaker = sc.get_speaker('FS2i2')
# one_mic = sc.get_microphone('FS2i2')#

# record and play back one second of audio:
# data = one_mic.record(samplerate=48000, numframes=48000)
# one_speaker.play(data/numpy.max(data), samplerate=48000)

# alternatively, get a `Recorder` and `Player` object
# and play or record continuously:
with one_mic.recorder(samplerate=48000) as mic, one_speaker.player(
        samplerate=48000) as sp:
    for _ in range(1000):
        data = mic.record(numframes=1024)
        sp.play(data)
Пример #14
0
#if you have pulseudio 

import soundcard as sc

speakers = sc.all_speakers()
default_speaker = sc.default_speaker()
mics = sc.all_microphones()
default_mic = sc.default_microphone()
# search by substring:
one_speaker = sc.get_speaker('Scarlett')
one_mic = sc.get_microphone('Scarlett')
# fuzzy-search:
one_speker = sc.get_speaker('FS2i2')
one_mic = sc.get_microphone('FS2i2')
print(default_speaker)
print(default_mic)

# record and play back one second of audio:
data = default_mic.record(samplerate=44100, numframes=44100)
default_speaker.play(data/numpy.max(data), samplerate=44100)

# alternatively, get a `recorder` and `player` object and play or record continuously:
with default_mic.recorder(samplerate=44100) as mic, default_speaker.player(samplerate=44100) as sp:
    for _ in range(100):
        data = mic.record(numframes=1024)
        sp.play(data)
Пример #15
0
import soundcard as sc
import socket
import pickle
try:
    default_speaker = sc.default_speaker()
except:
    print('Error in speaker lookup')
mics = sc.all_microphones(include_loopback=True)
print(mics[0])
try:
    loopback = sc.get_microphone('Audio', include_loopback=True)
except:
    print('error in microphone binding')
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    print('created socket')

    # s.connect(('127.0.0.1',8001))
    with loopback.recorder(samplerate=48000) as mic, default_speaker.player(
            samplerate=48000) as sp:
        while True:
            data = mic.record(numframes=1024)

            # print(data)
            comp = pickle.dumps(data)
            s.sendto(comp, ('127.0.0.1', 8001))
            # sp.play(data)
Пример #16
0
        os.system(screen_clear)
        lines.reverse()
        for l in lines:
            print(l)

    def start_render_loop(self):
        while True:
            self._render()
            time.sleep(0.01667)


if __name__ == '__main__':

    import soundcard as sc

    from ..common import samplegen

    selections = sc.all_speakers()
    for i, s in enumerate(selections):
        print("{} : {}".format(i, s))

    s = int(input("Speaker Choice: "))
    s_name = selections[s].name

    mixin = sc.get_microphone(id=s_name, include_loopback=True)

    with mixin.recorder(samplerate=44100) as rec:
        ar = AudioRenderer(samplegen(rec), char="|")
        ar.start_render_loop()
Пример #17
0
import traceback

rate = 96000
soundSpeed = 343  # m/s
client = Spacebrew('mic_array', server='localhost')
client.addPublisher('000', 'range')
client.addPublisher('060', 'range')
client.addPublisher('120', 'range')
client.addPublisher('x', 'number')
client.addPublisher('y', 'number')
client.addPublisher('z', 'number')
client.addPublisher('vector', 'vector3')
client.start()

# open the mic array
mic = sc.get_microphone('Azure Kinect')


def crest_factor(signal):
    """
    Crest factor of a 1D signal
    """
    peak = np.amax(np.absolute(signal))
    rms = rms_flat(signal)
    if rms == 0:
        rms = .000001
    return peak / rms


def process(data):
    # separate the audio by channel
Пример #18
0
def get_default_device():
    default_speaker = sc.default_speaker().name
    default_speaker_microphone = sc.get_microphone(default_speaker,
                                                   include_loopback=True)
    return default_speaker_microphone
Пример #19
0
 def __init__(self, mixer_name):
     self.card = sc.get_microphone(mixer_name)
Пример #20
0
def get_interface(cfo):
    _test0 = soundcard.all_speakers()
    _test1 = soundcard.all_microphones()
    sp = soundcard.get_speaker(cfo.OUT_CARD_NAME)
    mc = soundcard.get_microphone(cfo.IN_CARD_NAME)
    return sp, mc
Пример #21
0
import soundcard
import aubio

import pygame

import colorsys

sample_rate = 44100

hop_size = round(sample_rate * 1 /
                 1000)  # we take a pitch measurement every hop_size frames
window = 2048  # number of previous frames analysed for each pitch measurement

pitcher = aubio.pitch("default", window, hop_size, sample_rate)

input_device = soundcard.get_microphone('Loopback')

pygame.init()
screen = pygame.display.set_mode((256, 256))


# Collapse octaves and map notes linearly between 0 and 1
def normalise(freq):
    base_freq = 440 * 2**(-29 / 12)  # guitar open sixth string (E2)

    if freq == 0:
        freq += base_freq
    while freq > base_freq * 2:
        freq /= 2
    while freq < base_freq:
        freq *= 2
Пример #22
0
 def __get_mic(self):
     if self.__input_name is None:
         return sc.default_microphone()
     else:
         return sc.get_microphone(self.__input_name, True)
Пример #23
0
 def get_channels(self, name):
     return sc.get_microphone(name).channels
Пример #24
0
if __name__ == "__main__":
    while True:
        try:
            while True:
                port_name = "Akai APC20 2"
                for port in mido.get_output_names():
                    if "Akai APC" in port:
                        port_name = port
                        break
                print("Opening MIDI Port", port_name)
                with mido.open_output(port_name) as apc_out:
                    clear()
                    while True:
                        speaker = sc.default_speaker()
                        loopback = sc.get_microphone(speaker.id,
                                                     include_loopback=True)
                        print("Using ", speaker.name)
                        try:
                            with loopback.recorder(samplerate=RATE,
                                                   channels=[0]) as mic:
                                cols = [0, 0, 0, 0, 0, 0, 0, 0]
                                smooth = [0, 0, 0, 0, 0, 0, 0, 0]
                                while True:
                                    if sc.default_speaker().id != speaker.id:
                                        print("Audio output changed.")
                                        break
                                    fft_leds(
                                        np.concatenate(
                                            mic.record(numframes=CHUNK)))
                        except RuntimeError:
                            print("Audio output lost.")
Пример #25
0
 def get_audio_context(self, name, channel=[0, 1, 2, 3, 4, 5, 6, 7]):
     m = sc.get_microphone(name)
     return m.recorder(samplerate=self.sample_rate, channels=channel)
Пример #26
0
import matplotlib.animation as animation
from matplotlib import style
import tkinter as tk
import numpy as np
import soundcard as sc
from scipy.io.wavfile import read

LARGE_FONT = ("Verdanna", 30)
style.use("ggplot")

f = Figure(figsize=(40, 15), dpi=100)
gs = f.add_gridspec(2, 5)

recordtime = 3

mic = sc.get_microphone('Shure')


def ReadWav(wavstrg):
    red = read(wavstrg)
    samps = []
    for k in red[1]:
        samps.append(k[1])
    samps = samps / np.max(samps)
    return samps


def MicRecord(mic):
    recording = mic.record(samplerate=44100, numframes=recordtime * 44100)
    recording = recording / np.max(recording)
    rec = []
Пример #27
0
		spiralOutFull(sleep)
		blinkDiagonally(sleep)

"""
92 93 94 95 96 97 98 99
84 85 86 87 88 89 90 91
76 77 78 79 80 81 82 83
68 69 70 71 72 73 74 75
60 61 62 63 64 65 66 67
52 53 54 55 56 57 58 59
44 45 46 47 48 49 50 51
36 37 38 39 40 41 42 43
"""

speaker = soundcard.get_speaker("Steinberg")
microphone = soundcard.get_microphone("Steinberg", include_loopback=True)
   
midiout = rtmidi.MidiOut()
available_ports = midiout.get_ports()
for port in available_ports:
	if "Ableton Push 2" in port and "MIDIOUT" not in port:
		device = int(port[-1])
midiout.open_port(device)
sleep = 0.02
turnOff()
prev = 0
color = randint(0, 127)
print("{} is the color.".format(color))
samples = 11200
milisec = 56
eighth = int(milisec / 8)