3
7

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 の SpeechRecognizer を用いて音声認識するためにWAVファイルを分割して投入

Posted at

音声ファイルの分割

Google Speech Recognitionを使って、音声認識が可能な最大ファイルサイズには制限があるようなので、以下で、ファイルを分割します。
(Google Speech RecognitionはWAVしか受け付けないので、違う場合は、ffmpeg などを使って変換しておいてください。)

pydubのsplit_on_silenceを使って、まず無音部分を検出して分割し、さらにまだファイルサイズが大きい場合は強制的に分割しています。
これで、datas_output/outputs/ というフォルダの下に、
output0.wav ... という通し番号がついたファイルに分割されます。

# ファイルの読み込み~無音部分での分割
# pydubにsplit_on_silenceというクラスがあるので、これを使う
# 注意:::時間がかかる
# -*- coding: utf-8 -*-
from pydub import AudioSegment
from pydub.silence import split_on_silence
import os
new_dir_path_recursive = 'datas_output/outputs/'
os.makedirs(new_dir_path_recursive, exist_ok=True)

# wavファイルのデータ取得
sound = AudioSegment.from_file("OUTPUT.wav", format="wav")

# wavデータの分割(無音部分で区切る)
# min_silence_len=2000	2000ms以上無音なら分割
# silence_thresh=-40	-40dBFS以下で無音と判定
# keep_silence=600	分割後500msは無音を残す
chunks = split_on_silence(sound, min_silence_len = 2000, silence_thresh = -45, keep_silence = 200, seek_step = 5)

kaisuu = 0
# 分割したデータ毎にファイルに出力
for i, chunk in enumerate(chunks):
    print(i)
    # duration
    duration_in_milliseconds = len(chunk)
  # ファイルサイズが大きい場合に分割する
    if duration_in_milliseconds > 400000:
       print(duration_in_milliseconds)
       # split sound in 200-second slices and export
       for ii, slice in enumerate(chunk[::200000]):
          with open("datas_output/outputs/output" + str(kaisuu) + ".wav" , "wb") as f:
             slice.export(f, format="wav")
             kaisuu += 1
    else:
       file_path = 'datas_output/outputs/output' + str(kaisuu) + '.wav'
       chunk.export(file_path, format="wav")
       kaisuu += 1

音声認識

上で分割したファイルを通し番号順に認識して、myfile.txt というファイルに書き込んでいきます。
なぜか、認識できないファイルがたまにあるので、そこはスキップして書き込みます。

import speech_recognition as sr
r = sr.Recognizer()
foo = open('myfile.txt', 'a')
text1 = None
for n in range(0,100):    #(12,14):
  # with sr.AudioFile("output_audio_file_0" + f'{n:02}'  + ".wav") as source:
  with sr.AudioFile("datas_output/outputs/output" + str(n)  + ".wav") as source:
    audio = r.record(source)
    try:
        text = r.recognize_google(audio, language='ja-JP', show_all=False)
        foo.write('\n')
        foo.write(str(text))
        print(n)
    except sr.RequestError as e:
        print(str(n) + ":Could not request results from Google Speech Recognition service; {0}".format(e))
        foo.write("\n" + str(n) + ":Could not request results from Google Speech Recognition service; {0}".format(e))
        continue
    except:
        foo.write("\n" + str(e) + ":" + str(n) + '--kesson--' + "\n")
        continue
foo.close()

パラメータはだいたいこんな感じかと思いますが、適宜調整してください。

3
7
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
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?