Last active
September 17, 2018 02:30
-
-
Save lefirea/ca5141176507c8d543542f09dc401164 to your computer and use it in GitHub Desktop.
PyAudioとpyworldの連携ができますた^^
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import numpy as np | |
import pyaudio | |
import pyworld as pw | |
import time | |
import threading | |
from pynput.keyboard import Key, Controller, Listener | |
#from scipy.io import wavfile | |
Chunk=1024*2 | |
Format=pyaudio.paInt16 | |
Channels=1 | |
Rate=16000 | |
QuitKeyPushed=False #Escキーが押されたかどうか | |
def on_press(key): | |
global listener | |
global QuitKeyPushed | |
try: | |
#通常キー | |
char=key.char | |
except: | |
#修飾キー | |
char=key | |
finally: | |
#print(char) | |
#Escキー or Qキーが押されたらプログラム終了 | |
if char==Key.esc or char=='q': | |
print('quit...') | |
QuitKeyPushed=True | |
listener.stop() | |
thread1.join() | |
def on_release(key): | |
pass | |
#キー入力監視 | |
def KeyLogger(): | |
try: | |
with Listener(on_press=on_press, on_release=on_release) as listener: | |
listener.join() | |
except: | |
pass | |
#音声変換 | |
def ChangeVoice(data): | |
data=np.frombuffer(data, dtype=np.int16).astype(np.float) | |
_f0, t=pw.dio(data, Rate) | |
f0=pw.stonemask(data, _f0, t, Rate) | |
sp=pw.cheaptrick(data, f0, t, Rate) | |
ap=pw.d4c(data, f0, t, Rate) | |
synthe=pw.synthesize(f0*1.5, sp, ap, Rate).astype(np.int16) | |
return synthe.tobytes() | |
#キー入力監視開始 | |
thread1=threading.Thread(target=KeyLogger) | |
thread1.start() | |
p=pyaudio.PyAudio() | |
stream=p.open(format=Format, | |
channels=Channels, | |
rate=Rate, | |
input=True, | |
output=True, | |
#frames_per_buffer=Chunk | |
) | |
#ストリーム開始 | |
stream.start_stream() | |
while stream.is_active(): | |
try: | |
data=stream.read(Chunk) | |
data=ChangeVoice(data) | |
stream.write(data) | |
if QuitKeyPushed==True: | |
break; | |
except: | |
print('except') | |
#listener.join()を誘発して終了 | |
keyboard=Controller() | |
keyboard.press(Key.esc) | |
keyboard.release(Key.esc) | |
thread1.join() | |
break; | |
finally: | |
pass | |
stream.stop_stream() | |
stream.close() | |
p.terminate() | |
print('Stop Streaming...') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment