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)
def start(self): """ Starts the audio recording """ self.is_paused = False self.microphone = sc.default_microphone() self.speaker = sc.default_speaker()
def audio_test_soundcard(mode): import soundcard as sc mode = int(mode) c2 = pycodec2.Codec2(mode) conrate = c2.samples_per_frame() bitframe = c2.bits_per_frame() pa_rate = 8000 default_mic = sc.default_microphone() default_speaker = sc.default_speaker() print(default_mic, default_speaker) sc_config = {"samplerate": pa_rate, "blocksize": conrate} with default_mic.recorder(**sc_config,channels=1) as mic,\ default_speaker.player(**sc_config,channels=1) as sp: while 1: audio = mic.record(numframes=conrate) #.transpose() audio = audio.flatten() audio = audio * 32767 audio = audio.astype("<h") c2_bits = c2.encode(audio) audio = c2.decode(c2_bits) audio = audio.astype("float") audio = audio / 32767 sp.play(audio)
def get_default_mic_device(): default_mic_name = "" try: default_mic_name = sc.default_microphone().name except: pass return default_mic_name
def __init__(self, fs, nf): self.__sample_rate = fs self.__num_of_frames = nf self.__frame_buffer = np.zeros(self.__num_of_frames) self.__default_mic = sc.default_microphone() thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start()
def __init__(self, rate=4000, chunksize=1024): self.rate = rate self.chunksize = chunksize self.mic = sc.default_microphone() self.lock = threading.Lock() self.stop = False self.frames = [] self.t = threading.Thread(target=self.capture_frames, daemon=True) atexit.register(self.close)
def record_and_play(): #methods = ['GET', 'POST']): #filename = 'bear_growl_y.wav' #rb = wave.open(filename, 'rb') #file_sr = rb.getframerate() #wavfile = read(filename)[1] mysp = sc.default_speaker() mymic = sc.default_microphone() rate = 48000 data = mymic.record(samplerate=rate, numframes=10 * rate) #mysp.play(wavfile/np.max(wavfile), samplerate = file_sr) mysp.play(data / np.max(data), samplerate=rate)
def print_all_devices() -> None: print("speakers") spk_all = sc.all_speakers() spk_default = sc.default_speaker() for spk in spk_all: prefix = "*" if str(spk) == str(spk_default) else " " print(f"{prefix} {spk.name} id: {spk.id}") print("microphones") mic_all = sc.all_microphones() mic_default = sc.default_microphone() for mic in mic_all: prefix = "*" if str(mic) == str(mic_default) else " " print(f"{prefix} {mic.name} id: {mic.id}")
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()
def main(): CHUNK = 8192 # number of data points to read at a time RATE = 48000 # time resolution of the recording device (Hz) default_mic = sc.default_microphone() try: with default_mic.recorder(RATE, channels=1, blocksize=CHUNK // 16) as rec: while True: data = rec.record(numframes=CHUNK) data = data.reshape((len(data))) peak_f = find_peak(data, fs=RATE) print("peak frequency: %d Hz" % peak_f) except KeyboardInterrupt: print()
def __init__( self, samplerate: int = 48000, channels: Union[int, List[int]] = None, blocksize: int = 1024, device=None, loop=None, ): if device is None: device = sc.default_microphone() self._device = device self._samplerate = samplerate self._channels = channels self._blocksize = blocksize super().__init__(defaultSubscriptionType=asyncio.Queue, logger=self._log)
def __init__(self, **kwargs): super(TTSDatasetRecorderWidget, self).__init__(**kwargs) self.line_index = -1 self.book_file = "text.txt" with open(self.book_file, encoding="utf-8") as f: self.lines = [line.replace("\n", "") for line in f.readlines()] self.fs = 48000 desktop_path = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') self.out_dir = os.path.join(desktop_path, "TTS_dataset_recordings") os.makedirs(self.out_dir, exist_ok=True) self.reading_speed_text = "Reading speed: %100" self.load_next_sentence() self.reading_speed = 100 self.mic = sc.default_microphone() self.edit_text = False self.edit_text_button_text = "Edit Text" self.tmpSentence = ""
def __init__( self, samplerate: int = 48000, channels: Union[int, List[int]] = None, blocksize: int = 1024, device=None, loop=None, gain=1, ): if device is None: device = sc.default_microphone() self._device = device self._samplerate = samplerate self._channels = channels self._blocksize = blocksize self._gain = gain super().__init__(defaultSubscriptionType=asyncio.Queue, logger=self._log)
def test(self): self.sound_cards = soundcard.all_speakers() self.mics = soundcard.all_microphones() if len(self.sound_cards) > 0: self.sound_card_present = True self.default_sound_card = str(soundcard.default_speaker()).replace( "<", "").replace(">", "") else: self.sound_card_present = False self.default_sound_card = "No default sound card found. May not be enabled or plugged in." if len(self.mics) > 0: self.mic_present = True self.default_mic = str(soundcard.default_microphone()).replace( "<", "").replace(">", "") else: self.mic_present = False self.default_mic = "No default mic found. May not be enabled or plugged in." return self
def run(): print("connecting to socket server") # client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # client.connect((TCP_IP_ADDR, TCP_PORT_NO)) print("getting all microphones") # all_microphones = sc.all_microphones(include_loopback=True) # print("got all microphones: {}".format(all_microphones)) # loopback = next((microphone for microphone in all_microphones if microphone.isloopback and microphone.name.find('Speakers') != -1), None) loopback = sc.default_microphone() if loopback is None: print("No loopback device detected, exiting...") exit(1) print("Found a loopback microphone with: {}".format(loopback)) try: with loopback.recorder( samplerate=44100, channels=2) as mic: #, wave.open('test.wav', 'wb') as wav: # wav.setparams((1, 2, 44100, 0, 'NONE', 'NONE')) spk = next(speaker for speaker in sc.all_speakers() if speaker.name.find('ODAC') != -1) print(spk) # mic.__enter__() # while True: while True: try: data = loopback.record(1024, 44100) spk.play(data, 44100) # byte = data.tobytes() # wav.writeframes(byte) # mic.flush() # byte = bytes('testing', 'utf-8') # client.send(byte) # sys.stdout.flush() # client.sendto(byte, (UDP_IP_ADDR, UDP_PORT_NO)) # mic.flush() except Exception as e: print("Uh oh... failed: {}".format(e)) exit(1) except KeyboardInterrupt: # client.close() wav.close()
def mic_audio(config, inq, outq): """ Pull audio off the default microphone in 8k, 1 channel, scale it into 16bit shorts since soundcard uses floats, and put them in the outq. inq is unconnected here. """ import soundcard as sc default_mic = sc.default_microphone() # print(default_mic) conrate = config.codec2.conrate with default_mic.recorder(samplerate=8000, channels=1, blocksize=conrate) as mic: while 1: audio = mic.record(numframes=conrate) #we get "interleaved" floats out of here, in a numpy column ([[][][]])(hence the flatten even though it's a single audio channel) audio = audio.flatten( ) * 32767 #scales from -1,1 to signed 16bit int values #rest of the system works in little endian shorts, so we scale it up and convert the type audio = audio.astype("<h") outq.put(audio)
def get_input_device_list(): """Return tuple containing: list of audio devices (tuples of SoundCard Device instance and name), index of default input device on this list, index of default loopback device on this list """ devices = [(mic, mic.name) for mic in soundcard.all_microphones(include_loopback=True)] try: default_output_name = soundcard.default_speaker().name default_loopback = next( (mic for mic in soundcard.all_microphones(include_loopback=True) if mic.isloopback and default_output_name in mic.name), None) except RuntimeError: default_loopback = None try: default_input = soundcard.default_microphone() except RuntimeError: default_input = None return devices, _find_device_on_list(default_input, devices), \ _find_device_on_list(default_loopback, devices)
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
def normalize_loudness(dev_l, dev_r): global mic_data pulse = pulsectl.Pulse('SplitSpkr') devices = [dev_l, dev_r] pulse_devices = get_pulse_speakers(pulse, devices) mic = sc.default_microphone() for m in sc.all_microphones(): if m.name == "USB PnP Audio Device Analog Mono": mic = m sample_volume(devices, mic) sample_volume(devices, mic) l_vol = mic_data[0] r_vol = mic_data[1] print(mic_data) if l_vol > r_vol: pulse.volume_set_all_chans(pulse_devices[0], \ (r_vol/l_vol)) else: pulse.volume_set_all_chans(pulse_devices[1], \ (l_vol/r_vol)) sample_volume(devices, mic) print(mic_data) return [dev_l, dev_r]
def __init__(self, chunk=2048, rate=44100): self.chunk = chunk self.rate = rate self.speaker = soundcard.default_speaker() self.mic = soundcard.default_microphone() self.shairport = None
parser = argparse.ArgumentParser(description="NieR Automata Fishing Bot") parser.add_argument("--debug", action="store_true", help="Debug Stereo Mix", default=False) parser.add_argument("--window", type=int, help="Number of times to sample audio per second", default=10) parser.add_argument("--cast-time", type=int, help="Seconds to wait before reeling back in", default=20) parser.add_argument("--threshold", type=float, required=True, help="Audio amplitude to treat as a fish on the line") parser.add_argument("--frequency", type=int, help="Frequency of Sound Device", default=48000) args = parser.parse_args() DEBUG = args.debug WINDOW = args.window CASTINGTIME = args.cast_time THRESHOLD = args.threshold FREQUENCY = args.frequency speaker = soundcard.default_speaker() mic = soundcard.default_microphone() def wait_for_catch(alldata): with mic.recorder(samplerate=FREQUENCY) as recorder: for _ in range(WINDOW * CASTINGTIME): data = recorder.record(numframes=(FREQUENCY // WINDOW)) if DEBUG: alldata.append(data) volume = 0.0 for frame in data: volume += abs(frame[0]) + abs(frame[1]) volume /= FREQUENCY / WINDOW print(volume) if volume >= THRESHOLD: print("CATCH!") print('\a')
def __get_mic(self): if self.__input_name is None: return sc.default_microphone() else: return sc.get_microphone(self.__input_name, True)
konwersja tablicy data """ def convert_sound_data(data): max_amplitude = 2**15 - 1 data = max_amplitude * data data = data.astype(np.int16).tostring() return data speakers = sc.all_speakers() default_speaker = sc.default_speaker() mics = sc.all_microphones() default_mic = sc.default_microphone() amp = 100 #wzmocnienie samplerate = 48000 #f_probkowania channels = 2 numframes = 150000 #liczba_probek chanel_left = np.array([[1, 0]]) chanel_right = np.array([[0, 1]]) print(default_mic) print(default_speaker) print('start nagrywania \n') data = default_mic.record(samplerate=samplerate, channels=channels,
def test_default_blockless_record(): recording = soundcard.default_microphone().record(None, 44100)
def test_default_record(): recording = soundcard.default_microphone().record(1024, 44100) assert len(recording == 1024)
def scope(model, buf_size=2000, fs=44100): default_mic = sc.default_microphone() print("oscilloscope: listening on ", default_mic) instructions() trig_level = 0.01 # trigger value for input waveform gains = [1, 1] # gains for input and output # allocate storage for 'screen' screen = np.zeros((imHeight, imWidth, 3), dtype=np.uint8) # 3=color channels xs = np.arange(imWidth).astype(np.int) # x values of pixels (time samples) while (1): # keep looping until someone stops this try: # sometimes the mic will give a RunTimeError while you're reizing windows with default_mic.recorder(samplerate=fs) as mic: audio_data = mic.record( numframes=buf_size) # get some audio from the mic audio_data *= gains[0] # apply gain before activation bgn = find_trigger(audio_data[:, 0], thresh=trig_level) # try to trigger layer_in_dim = model.in_chunk_size # length of input layer if bgn is not None: # we found a spot to trigger at end = min(bgn + layer_in_dim, buf_size) # don't go off the end of the buffer pad_len = max(0, layer_in_dim - (end - bgn)) # might have to pad with zeros padded_data = np.pad(audio_data[bgn:end, 0], (0, pad_len), 'constant', constant_values=0) draw_activations(screen, model, padded_data, xs, trig_level=trig_level, gains=gains) # draw left channel else: draw_activations(screen, model, audio_data[0:layer_in_dim, 0] * 0, xs, trig_level=trig_level, gains=gains) # just draw zero line key = cv2.waitKeyEx(1) & 0xFF # keyboard input # Controls: (Couldn't get arrow keys to work.) if (key != -1) and (key != 255): #print('key = ',key) pass if ord('q') == key: # quit key break elif ord('=') == key: gains[0] *= 1.1 elif ord("-") == key: gains[0] *= 0.9 elif ord(']') == key: # right bracket gains[1] *= 1.1 elif ord('[') == key: # left bracket gains[1] *= 0.9 elif ord("'") == key: trig_level += 0.02 elif ord(";") == key: # letter p trig_level -= 0.02 except: pass return
def record(t, fs): mic = sc.default_microphone() samples = fs * t x = mic.record(samples, fs) return (x)
import soundcard as sc """ print(sc.all_speakers()) print("--------------------") print(sc.all_microphones()) print("---------------") """ print(sc.default_speaker()) print(sc.default_microphone()) m = sc.default_microphone() s = sc.default_speaker() i = 0 darray = [] with m.recorder(48000, blocksize=512) as r, s.player(48000, blocksize=512) as p: while True: print("Recording...") i += 1 d = r.record(512 * 1000) print(i, d.shape) p.play(d * 10) darray.append(d * 10) print("Playing...") for da in darray: p.play(d)
def setupOscil(): global imWidth = 1024 global imHeight = 512 global default_mic = sc.default_microphone() global screen = np.zeros((imHeight,imWidth,3), dtype=np.uint8) global xs = np.arange(imWidth).astype(np.int)