4
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonで簡単に音声認識を導入

Posted at

#音声toTXT変換

import speech_recognition as sr
import soundfile as sf
from io import BytesIO
import os

r = sr.Recognizer()

def analyze_wav(wavfile):
    try:
        adata, samplerate = sf.read(BytesIO(wavfile.read()))

        newpath = "new_file.wav"

        path_tmp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")

        if not os.path.exists(path_tmp):
            os.mkdir(path_tmp)

        savepath = os.path.join(path_tmp, newpath)
        sf.write(savepath, adata, samplerate)

        with sr.AudioFile(savepath) as src:
            audio = r.record(src)
        txt = r.recognize_google(audio, language='ja-JP')

        return txt
    except:
        import traceback
        traceback.print_exc()

#サーバーで利用する場合(Flask)

from flask import Flask, request, abort

import speech_recognition as sr
import soundfile as sf
from io import BytesIO
import os

r = sr.Recognizer()

@app.route("/webapp", methods=['POST'])
def webapp():
    wavdata = request.files["file"].stream
    txt = analyze_wav(wavdata)
    return txt

def analyze_wav(wavfile):
    try:
        adata, samplerate = sf.read(BytesIO(wavfile.read()))

        newpath = "new_file.wav"

        path_tmp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")

        if not os.path.exists(path_tmp):
            os.mkdir(path_tmp)

        savepath = os.path.join(path_tmp, newpath)
        sf.write(savepath, adata, samplerate)

        with sr.AudioFile(savepath) as src:
            audio = r.record(src)
        txt = r.recognize_google(audio, language='ja-JP')

        return txt
    except:
        import traceback
        traceback.print_exc()
4
9
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
4
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?