问题描述
我在谷歌语音识别中遇到关于长音频文件的问题..所以我决定在 15 秒内分割我的音频文件..每次我发送前 15 秒到语音识别然后第二个 15 秒等等.. .
但是现在当我使用 pydub lib 时,它拆分了音频文件,拆分后的返回值不是文件扩展名,因为 API 需要一个文件扩展名作为参数(我标记了错误) 它说“给定的音频文件必须是文件名字符串或类似文件的对象”
import speech_recognition as sr
import numpy
from os import path
AUdio_FILE = "OAF_back_happy.wav"
from pydub import AudioSegment
sound = AudioSegment.from_wav("OAF_back_happy.wav")
halfway_point = len(sound) // 2
split = []
split.append(sound[:halfway_point])
split.append(sound[halfway_point:])
r = sr.Recognizer()
words=1
for x in split:
with sr.AudioFile(x) as source: #<-----
audio = r.record(source) # read the entire audio file
try:
# for testing purposes,we're just using the default API key
# to use another API key,use `r.recognize_google(audio,key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
ans = r.recognize_google(audio)
print("Google Speech Recognition thinks you said " +ans)
for x in ans:
if (x.isspace()) == True:
words+=1
print(words)
except sr.UnkNownValueError:
print("Google Speech Recognition Could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
编辑:如评论中所述,我不想导出文件,因为我正在使用服务器并且我不想将相同的文件“两次”放置
解决方法
未经测试,因为我懒得安装我不使用的软件包,但这就是我的意思。
for x in split:
b = io.BytesIO()
x.export(b)
b.seek(0)
with sr.AudioFile(b) as source:
audio = r.record(source)