我想将录音从 Facebook Messenger 转换为文本。
以下是使用 Facebook 的 API 发送 .mp4 文件的示例:
https://cdn.fbsbx.com/v/t59.3654-21/15720510_10211855778255994_5430581267814940672_n.mp4/audioclip-1484407992000-3392.mp4?oh=a78286aa96c9dea29e5d07854194801c&oe=587C3833
所以这个文件只包含音频(不是视频),我想把它转换成文本。
此外,我想尽快完成,因为我将在几乎实时的应用程序中使用生成的文本(即用户发送 .mp4 文件,脚本将其转换为文本并显示回来)。
我找到了这个例子 https://github.com/Uberi/speech_recognition/blob/master/examples/audio_transcribe.py
这是我使用的代码:
import requests
import speech_recognition as sr
url = 'https://cdn.fbsbx.com/v/t59.3654-21/15720510_10211855778255994_5430581267814940672_n.mp4/audioclip-1484407992000-3392.mp4?oh=a78286aa96c9dea29e5d07854194801c&oe=587C3833'
r = requests.get(url)
with open("test.mp4", "wb") as handle:
for data in r.iter_content():
handle.write(data)
r = sr.Recognizer()
with sr.AudioFile('test.mp4') as source:
audio = r.record(source)
command = r.recognize_google(audio)
print command
但我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Asterios\Anaconda2\lib\site-packages\speech_recognition\__init__.py", line 200, in __enter__
self.audio_reader = aifc.open(aiff_file, "rb")
File "C:\Users\Asterios\Anaconda2\lib\aifc.py", line 952, in open
return Aifc_read(f)
File "C:\Users\Asterios\Anaconda2\lib\aifc.py", line 347, in __init__
self.initfp(f)
File "C:\Users\Asterios\Anaconda2\lib\aifc.py", line 298, in initfp
chunk = Chunk(file)
File "C:\Users\Asterios\Anaconda2\lib\chunk.py", line 63, in __init__
raise EOFError
EOFError
有任何想法吗?
编辑:我想在 pythonanywhere.com 的免费计划上运行脚本,所以我不确定如何在那里安装像 ffmpeg 这样的工具。
编辑2:如果你运行上面的脚本,用这个“http://www.wavsource.com/snds_2017-01-08_2348563217987237/people/men/about_time.wav”替换url并将“mp4”更改为“wav”,它工作正常。所以它肯定与文件格式有关。
最佳答案
最后我找到了解决方案。我把它贴在这里以防将来对某人有帮助。
幸运的是,pythonanywhere.com 预装了 avconv(avconv 类似于 ffmpeg)。
所以这里有一些有效的代码:
import urllib2
import speech_recognition as sr
import subprocess
import os
url = 'https://cdn.fbsbx.com/v/t59.3654-21/15720510_10211855778255994_5430581267814940672_n.mp4/audioclip-1484407992000-3392.mp4?oh=a78286aa96c9dea29e5d07854194801c&oe=587C3833'
mp4file = urllib2.urlopen(url)
with open("test.mp4", "wb") as handle:
handle.write(mp4file.read())
cmdline = ['avconv',
'-i',
'test.mp4',
'-vn',
'-f',
'wav',
'test.wav']
subprocess.call(cmdline)
r = sr.Recognizer()
with sr.AudioFile('test.wav') as source:
audio = r.record(source)
command = r.recognize_google(audio)
print command
os.remove("test.mp4")
os.remove("test.wav")
在免费计划中,
cdn.fbsbx.com
不在 pythonanywhere 网站的白名单中,所以我无法使用 urllib2
下载内容。我联系了他们,他们在 1-2 小时内将域添加到白名单中!因此,即使我使用的是免费套餐,也非常感谢并祝贺他们提供的优质服务。
关于python - 在python中将mp4声音转换为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41525200/