LoginSignup
2
2

More than 1 year has passed since last update.

SpeechRecognitionで遊んでみたよ

Posted at

詠唱したら魔法打てないかな、なんて思っていたので、Pythonの音声認識モジュールであるSpeechRecognitionで遊んでみました。誰かナノマシンつくってくれないかな。
Python - SpeechRecognition

SpeechRecognitionのインストール

cmd
pip install SpeechRecognition

みんな大好きpipコマンドです。

wavファイルで入力して文字列に変換

コードはこんな感じ。

test.py
import speech_recognition as sr

r = sr.Recognizer()

with sr.AudioFile("./aftereat.wav") as source:
    audio = r.record(source)

text = r.recognize_google(audio, language = 'ja-JP')

print(text)

ファイルは.wav拡張子じゃないと通らないので気をつける。
拡張子を無理やり変えてもだめです。ちゃんとコンバート、コンバート。
あとちゃんとパスを指定しましょう。

音声ファイルはこちらからお借りしました。
Booth - Afterifk Kawaii Voice β

Let's 実行

cmd
python test.py
ごちそうさま

きゃーコマンドプロンプトちゃんkawaiiデス!
彼女と結婚できる日もそう遠くないでしょう。

リアルタイム入力で字幕付け

リアルタイム入力での文字起こしでは、SpeechRecognitionのほかに、PyAudioというモジュールが必要になってきます。こちらもpipコマンドでインストールしておきましょう。

cmd
pip install pyaudio

ではコードはこんな感じ。

test.py
import speech_recognition as sr
import pyaudio, time

SAMPLERATE = 44100

def callback(in_data, frame_count, time_info, status):
    global sprec 

    try:
        audiodata = sr.AudioData(in_data,SAMPLERATE,2)
        sprec_text = sprec.recognize_google(audiodata, language='ja-JP')
        print(sprec_text)
    except sr.UnknownValueError:
        pass
    except sr.RequestError as e:
        pass
    finally:
        return (None, pyaudio.paContinue)
    
def main():
    global sprec 
    sprec = sr.Recognizer()
    audio = pyaudio.PyAudio() 
    stream = audio.open(
        format = pyaudio.paInt16,
        rate = SAMPLERATE,
        channels = 1, 
        input_device_index = 1,
        input = True, 
        frames_per_buffer = SAMPLERATE*2,
        stream_callback=callback
    )
    
    stream.start_stream()
    while stream.is_active():
        time.sleep(0.1)
    
    stream.stop_stream()
    stream.close()
    audio.terminate()

if __name__ == '__main__':
    main()

実行結果は以下の通り

cmd
python test.py
おはよう
フェリシアです
おねむ です
あめんぼあおいよ あいうえお
ニセコ

私は「おはよう ふぇりしあです おねむです あめんぼあおいよあいうえお すごい」とマイクに向かって入力したので結構精度高いみたいです。というかふぇりの名前がカタカナで出力されたのですが、これはreconize_google()が優秀だったのかな?

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2