def _test_microphone(self): stream = PyAudio().open( format=paInt16, channels=1, rate=self.sample_rate, input=True, frames_per_buffer=8000 ) stream.start_stream() self._read(stream)
class Sound: """Generate sound. Requires PyAudio & NumPy.""" def __init__(self, rate=44100, channels=1): # Suppress Jack and ALSA error messages on Linux: https://github.com/rtmrtmrtmrtm/weakmon/blob/master/weakaudio.py nullfd = os.open("/dev/null", 1) oerr = os.dup(2) os.dup2(nullfd, 2) self.stream = PyAudio().open(format=paFloat32, channels=channels, rate=rate, output=True) os.dup2(oerr, 2) os.close(oerr) os.close(nullfd) return def play(self, frequency=440, length=1.0, volume=1.0, rate=44100): """Play sine wave at frequency, for length, at rate parameters values.""" self.stream.stop_stream() self.stream.start_stream() wave = concatenate( [sin(arange(length * rate) * frequency * pi * 2 / rate)]) * volume self.stream.write(wave.astype(float32).tostring()) return
class Ava(AvaSkills): def __init__(self): super().__init__(self) self.interpreter = Interpreter.load(settings.RASA_MODEL_DIR) self.stream = PyAudio().open(format=paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024, output_device_index=0) self.config = pocketsphinx.Decoder.default_config() self.config.set_string( '-hmm', path.join(settings.SPHINX_MODEL_DIR, 'en-us/en-us')) self.config.set_string( '-dict', path.join(settings.SPHINX_MODEL_DIR, 'en-us/cmudict-en-us.dict')) self.config.set_string('-keyphrase', settings.WAKE_PHRASE) self.config.set_float('-kws_threshold', 1e+20) self.config.set_string('-logfn', 'text.log') self.decoder = pocketsphinx.Decoder(self.config) self.listen_for_wake() def listen_for_wake(self): self.stream.start_stream() self.decoder.start_utt() if (not self.play_mp3("startup_greeting.mp3")): self.get_tts( text= f"Hi, my name is Ava. If you need help, just say the wake command: {settings.WAKE_PHRASE}.", file_name="startup_greeting.mp3") print("Listening for wake word...") while True: buf = self.stream.read(1024) if buf: self.decoder.process_raw(buf, False, False) else: break if self.decoder.hyp() != None: print(f"Key phrase '{settings.WAKE_PHRASE}' detected...") if (not self.play_mp3("wake_chime.mp3")): exit() if (not self.play_mp3("wake_greeting.mp3")): self.get_tts(text="How can I help?", file_name="wake_greeting.mp3") self.listen_for_input() self.decoder.end_utt() print("Waiting for wakeup ...") self.decoder.start_utt() def get_tts(self, text, file_name, save=True): print("Converting text to speech...") polly_client = boto3.Session( aws_access_key_id=keys.POLLY_ACCESS_KEY_ID, aws_secret_access_key=keys.POLLY_SECRET_ACCESS_KEY, region_name='us-west-2').client('polly') response = polly_client.synthesize_speech(VoiceId='Joanna', OutputFormat='pcm', SampleRate="16000", Text=text) data = response['AudioStream'].read() self.play_byte(data) if save: print("Saving to mp3 file...") AudioSegment(data=data, sample_width=2, frame_rate=16000, channels=1).export(out_f=settings.MEDIA_DIR + file_name, format="mp3") def play_byte(self, stream): try: print("Playing byte stream...") play( AudioSegment(data=stream, sample_width=2, frame_rate=16000, channels=1)) except Exception as e: print("Error playing file...", e) def play_mp3(self, audio_file, save=True): file_path = settings.MEDIA_DIR + audio_file is_file = path.isfile(file_path) if is_file: try: print("Playing audio...") play(AudioSegment.from_mp3(file_path)) except Exception as e: print("Error playing file...", e) return False else: print("Audio file not found...") return False return True def listen_for_input(self): sr = speech_recognition.Recognizer() mic = speech_recognition.Microphone() hyp = None with mic as source: sr.adjust_for_ambient_noise(source) try: print("Listening...") audio = sr.listen(source, timeout=2) print("Decoding...") hyp = sr.recognize_google(audio) except speech_recognition.WaitTimeoutError as e: print("No input detected timeout...") except speech_recognition.UnknownValueError as e: if (not self.play_mp3("decode_error.mp3")): self.get_tts( text= "I'm sorry, but I was not able to understand that command.", file_name="decode_error.mp3") except speech_recognition.RequestError as e: print("Google request error: ", e) print("Running backup decode Sphinx...") try: hyp = sr.recognize_google(audio) except speech_recognition.UnknownValueError as e: print("Sphinx recognition error: ", e) if (not self.play_mp3("decode_error.mp3")): self.get_tts( text= "I'm sorry, but I was not able to understand that command.", file_name="decode_error.mp3") else: t0 = time() self.process_input_intent(hyp) print(f"Time to process command: {time() - t0}") def process_input_intent(self, hypothesis): print("Processing intent...") print(f"HYPOTHESIS:{hypothesis}") result = self.interpreter.parse(hypothesis) intent = result['intent']['name'] confidence = result['intent']['confidence'] print(f"INTENT: {intent}") print(f"CONFIDENCE_SCORE: {confidence}") try: print("Executing intent action...") response = getattr(self, intent)(result) print(f"RESULT: {response}") if (response): self.respond_intent_result(response) except Exception as e: print(f"Failed intent action...\n\tERROR: {e} ") def respond_intent_result(self, result): print(f"RESPONSE: {result['tts']}") if (not self.play_mp3(result['file'])): self.get_tts(text=result['tts'], file_name=result['file'], save=result['save'])
def audio_freq(): # Значення крайніх нот у моєму випадку (шестиструнна гітара в строї Ре) note_min = 60 # Нота До 4-ї октави note_max = 71 # Нота Сі 4-ї октави sample_freq = 22050 # Частота кадру в герцах # Від збільшення цих констант залежить швидкість оновлення частоти. frame_size = 2048 # Кількість зразків у кадрі frames_per_fft = 16 # Кількість кадрів для середнього значення ШПФ samples_per_fft = frame_size * frames_per_fft # Кількість зразків на ШПФ freq_step = sample_freq / samples_per_fft # Крок частоти # Отримання мінімального та максимального показника для наших нот в межах ШПФ. def note_to_fftbin(n): return 440 * 2.0 ** ((n - 69) / 12.0) / freq_step imin = max(0, int(numpy.floor(note_to_fftbin(note_min - 1)))) imax = min(samples_per_fft, int(numpy.ceil(note_to_fftbin(note_max + 1)))) # Визначення простору для ШПФ. buf = numpy.zeros(samples_per_fft, dtype=numpy.float32) # Функція вікна Хеннінга. window = 0.5 * (1 - numpy.cos(numpy.linspace(0, 2*numpy.pi, samples_per_fft, False))) # Відкриваємо аудіо потік. stream = PyAudio().open(format=paInt16, channels=1, rate=sample_freq, input=True, frames_per_buffer=frame_size) stream.start_stream() # Отримуємо дані, поки потік відкритий. while stream.is_active(): # Оновлюємо буфер та приймаємо нові дані. buf[:-frame_size] = buf[frame_size:] buf[-frame_size:] = numpy.fromstring(stream.read(frame_size), numpy.int16) # Запускаємо ШПФ в буфері в межах вікна. fft = numpy.fft.rfft(buf * window) # Отримуємо максимально повторювану частоту в діапазоні. freq = (numpy.abs(fft[imin:imax]).argmax() + imin) * freq_step # Запис відображення ноти (get_note) у файл freqs.txt freq_save(get_note(freq)) # Правильно закриваємо аудіо потік. stream.stop_stream() stream.close() stream.terminate()