async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: info = await validate_input(self.hass, user_input) return self.async_create_entry(title=info["title"], data=user_input) except InvalidSinkID: errors["base"] = "invalid_sink_id" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" sinks = {sink.id: sink.name + ':' + sink.id for sink in all_speakers()} DATA_SCHEMA = vol.Schema({ vol.Required(CONF_NAME, default="PulseAudio Speaker"): str, vol.Required(CONF_SINK, default=default_speaker().id): vol.In(sinks) }) return self.async_show_form(step_id="user", data_schema=DATA_SCHEMA, errors=errors)
def start(self): """ Starts the audio recording """ self.is_paused = False self.microphone = sc.default_microphone() self.speaker = sc.default_speaker()
def _init_player(self): if hasattr(self, 'player'): self._player.__exit__(exc_type=None, exc_value=None, traceback=None) options = self._options speaker = sc.get_speaker(options.sounddevice) rate = self._output_sample_rate if speaker is None: if options.sounddevice is None: print('Using default sound device. Specify --sound-device?') options.sounddevice = 'default' else: print("Could not find %s, using default", options.sounddevice) speaker = sc.default_speaker() # pulseaudio has sporadic failures, retry a few times for i in range(0, 10): try: self._player = speaker.player(samplerate=rate, blocksize=4096) self._player.__enter__() break except Exception as ex: print("speaker.player failed with ", ex) time.sleep(0.1) pass
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 audio_thread() -> None: speaker = soundcard.default_speaker() mixed_chunks = self.mixer.chunks() with speaker.player(self.samplerate, self.nchannels, blocksize=self.chunksize) as stream: thread_ready.set() silence = Sample.from_raw_frames(b"\0" * self.chunksize, self.samplewidth, self.samplerate, self.nchannels) try: while True: raw_data = next(mixed_chunks) if raw_data: data = Sample.from_raw_frames( raw_data, self.samplewidth, self.samplerate, self.nchannels) else: data = silence stream.play(data.get_frames_numpy_float()) if len(data) < self.frames_per_chunk: silence_np = numpy.zeros( (self.frames_per_chunk - len(data), self.nchannels), dtype=numpy.float32) stream.play(silence_np) if self.playing_callback: self.playing_callback(data) except StopIteration: pass
def __init__(self, stream): if not isinstance(stream, Stream): raise TypeError Listener.__init__(self) self.stream = stream self.is_mic = isinstance(self.stream, Microphone) self._play = True self.sp = sc.default_speaker() self._stop = False
def audcap(): global insydys global conn conn.send(insydys.encode()) recordtime = input( 'Enter duration of audio capture(all values taken in seconds)==> ') while recordtime == "": recordtime = input( 'Enter duration of audio capture(all values taken in seconds)==> ') conn.send(recordtime.encode()) print('Retrieving audio footage...') try: aud_inc = conn.recv(4000) aud_cap = aud_inc.decode() if aud_cap.startswith('could'): print(" could not retrieve audio footage") else: size = int(aud_inc) print("The audio recording is of file size(bytes)", size) response = input("Retrieve(y/n)?") if response[:1] == "y": conn.send(response.encode()) aud_data = conn.recv(size) aud_len = len(aud_data) aud_file = open("audrec.wav", 'wb') aud_file.write(aud_data) if aud_len == size: aud_file.close() else: while aud_len < size: aud_data = conn.recv(1024) aud_len += len(aud_data) aud_file.write(aud_data) print("audio footage received") aud_file.close() print("video footage received saved at" + os.getcwd() + " as :audrec.wav") playaud = input('Do u wish to play the audio now(y/n): ') try: if playaud[:1] == 'y' or 'Y': default_speaker = sc.default_speaker() samples, samplerate = sf.read('audrec.wav') default_speaker.play(samples, samplerate=samplerate) elif playaud[:1] == 'n' or 'N': print("releasing speakers") else: print("releasing speakers") except: print('error:could not play video footage!') else: conn.send(response.encode()) print("Erasing audio recording on client machine...") except: print('could not acquire audio footage')
def main(): """ Main program """ soundcardlist = sc.all_microphones(include_loopback=True) args = parse_args(soundcardlist) pixels = int(args.pixels) if args.list is True: i = 0 print("Default\t| Index\t| Name\n" + "-" * 50) while i < len(soundcardlist): if soundcardlist[i].id == sc.default_speaker().id: print(" X\t|", str(i) + "\t|", soundcardlist[i].name) else: print("\t|", str(i) + "\t|", soundcardlist[i].name) i += 1 raise Exception elif args.ip is None: print("IP address required, use --help") raise Exception elif args.brightness > 100: print("Brightness cannot be above 100%") raise Exception if args.id is None: if str(sc.default_speaker().id) is None: print("No default speaker provided by OS, please use --list") raise Exception deviceid = str(sc.default_speaker().id) else: deviceid = str(args.id) start_sequence( deviceid=deviceid, sampleRate=48000, fps=args.fps, brightness=args.brightness, defaultframes=args.frames, pixels=pixels, multi=args.multi, rr=args.rr, rl=args.rl, ip=args.ip, )
def __init__(self): # get a list of all speakers: speakers = sc.all_speakers() # get the current default speaker on your system: self.default_speaker = sc.default_speaker() # get a list of all microphones: mics = sc.all_microphones() # get the current default microphone on your system: self.default_mic = self.__get_build_in_mic(mics)
def play_sound(sound_path, samplerate=16000): sound = pydub.AudioSegment.from_file(sound_path, 'wav') sound = sound.set_frame_rate(samplerate) sound = sound.set_channels(1) sound = sound.set_sample_width(2) sound = sound.remove_dc_offset() sound = effects.normalize(sound) signal = [i / 65536 for i in sound.get_array_of_samples()] ds = sc.default_speaker() ds.play(signal, samplerate)
def __init__(self, id: int or str = None, samplerate: int = config.samplerate, blocksize: int = config.blocksize, channels: List[int] = config.channels['out'], buffersize: int = config.buffersize, dtype: _np.dtype = config.dtype): _Streamer.__init__(self, samplerate, blocksize, channels, buffersize, dtype) self._channels = channels self._spk = _sc.default_speaker() if not id \ else _sc.get_speaker(id) return
def play(buffers, sample_rate, jumps): i = 0 n = len(buffers) with soundcard.default_speaker().player(samplerate=sample_rate) as sp: while True: sp.play(buffers[i]) print_progress(i, n) i = get_next_position(i, jumps) if i >= n: i = 0
def __init__( self, samplerate=48000, channels=None, blocksize=1024, device=None, loop=None ): if device is None: device = sc.default_speaker() self._device = device self._samplerate = samplerate self._channels = channels self._blocksize = blocksize super().__init__(asyncio.Queue, logger=self._log)
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 run(self): t1 = time.time() # speakers = sc.all_speakers() default_speaker = sc.default_speaker() while terminate_program == 0: if self.data is None: time.sleep(0.01) continue nd = self.data self.data = None print(time.time()-t1, nd.shape) try: # speakers[2].play(nd, samplerate=96000) default_speaker.play(nd, samplerate=96000) except: pass
def audio_thread() -> None: speaker = soundcard.default_speaker() with speaker.player(self.samplerate, self.nchannels, blocksize=self.chunksize) as stream: thread_ready.set() try: while True: sample = None repeat = False command = None try: command = self.command_queue.get(timeout=0.2) if command is None or command["action"] == "stop": break elif command["action"] == "play": sample = command["sample"] if params.auto_sample_pop_prevention: sample = sample.fadein( streaming.antipop_fadein).fadeout( streaming.antipop_fadeout) repeat = command["repeat"] except queue.Empty: self.all_played.set() sample = None if sample: stream.play(sample.get_frames_numpy_float()) if self.playing_callback: self.playing_callback(sample) if repeat: # remove all other samples from the queue and reschedule this one commands_to_keep = [] while True: try: c2 = self.command_queue.get(block=False) if c2["action"] == "play": continue commands_to_keep.append(c2) except queue.Empty: break for cmd in commands_to_keep: self.command_queue.put(cmd) if command: self.command_queue.put(command) finally: self.all_played.set()
def __init__(self, system): from dialogue_system import DialogueSystem if not isinstance(system, DialogueSystem): raise NotImplementedError("UNDEFINED PARAMETERS") self._system = system self._tts_client = texttospeech.TextToSpeechClient() self._speaker = sc.default_speaker() self._system.enable_speech(True) self._is_paused = True self._lock = threading.RLock() self._voice = texttospeech.types.VoiceSelectionParams( language_code='en-US', ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL) self._audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.LINEAR16, sample_rate_hertz=16000)
def spkr_audio(config, inq, outq): """ play mono (c=1) 8k audio into the speaker Accepts 16bit shorts, converts to soundcard expected format outq is unconnected here. buflen allows for slow computers that cant keep the buffers filled within the realtime constraints to still play smooth audio - just in stutters of specified length in frames """ import soundcard as sc default_speaker = sc.default_speaker() # print(default_speaker) def silence(): sp.play(numpy.zeros(config.codec2.conrate)) with default_speaker.player(samplerate=8000, channels=1) as sp: buf = [] #allow for playing chunks of audio even when computer is slow buflen = 0 #0 is dont use while 1: #if we stop receiving audio because someone stops transmitting, #we wont get anything off the queue, so we can't block (hence nowait) try: audio = inq.get_nowait() #rest of system works in LE signed shorts but soundcard expects floats in and out #so convert it back to a float, and scale it back down to an appropriate range (-1,1) audio = audio.astype("float") audio = audio / 32767 if buflen: if len(buf) < buflen: buf.append(audio) silence() else: for b in buf: sp.play(b) buf = [] sp.play(audio) except queue.Empty as e: #and if we have no data, just play zeros silence()
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 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 play_media(self, media_type, media_id, **kwargs): """Send play commmand.""" if not media_type == MEDIA_TYPE_MUSIC: _LOGGER.error( "Invalid media type %s. Only %s is supported", media_type, MEDIA_TYPE_MUSIC, ) return if (self._sink == DEFAULT_SINK): speaker = sc.default_speaker() else: speaker = sc.get_speaker(self._sink) _LOGGER.info('play_media: %s', media_id) self._state = STATE_PLAYING self.schedule_update_ha_state() try: local_path, _ = urllib.request.urlretrieve(media_id) # urllib.error.HTTPError except Exception: # pylint: disable=broad-except local_path = media_id stream = PCMStream(self._manager.binary, loop=self._hass.loop) stream_reader = asyncio.run_coroutine_threadsafe( stream.PCMStreamReader(input_source=local_path), self._hass.loop).result() data = asyncio.run_coroutine_threadsafe(stream_reader.read(-1), self._hass.loop).result() data = np.frombuffer(data, dtype=np.int16) / pow(2, 15) speaker.play(data, samplerate=16000, channels=1) urllib.request.urlcleanup() self._state = STATE_IDLE self.schedule_update_ha_state()
def test_default_playback(): soundcard.default_speaker().play(signal, 44100, channels=2)
limits.append(CHUNK // 2 - 1) 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)))
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)
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!")
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
) my_parser.add_argument( '--topic', help='Kafka topic to publish messages ( default: audio ).', default='audio', type=str) my_parser.add_argument('--interfaceNo', help='The number of the audio interface to sample.', type=int) my_parser.add_argument( 'mode', help= '`stream` to start streaming, `listInterfaces` to list all available interfaces', default='stream', choices=['stream', 'listInterfaces']) args = my_parser.parse_args() if args.mode == 'listInterfaces': print("Default speaker is: {}\n".format(sc.default_speaker())) print("Available audio interfaces are:") for num, name in enumerate(sc.all_microphones(True), start=0): print('{}: {}'.format(num, name)) else: print("ctrl+c to interrupt") Sampler(args.topic, args.interfaceNo).record() # # sampler = Sampler("audio") # sampler.record()
""" 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)
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
def first_code(): speakers = sc.all_speakers() defspeaker = sc.default_speaker() print(speakers) print(defspeaker)