python - 声音文件中的 UnicodeDecodeError

标签 python python-3.x audio utf-8 speech-recognition

我正在尝试使用 Google 语音 API 在 Python 中制作语音识别器。我一直在使用和改编 here 中的代码(转换为Python3)。我在计算机上使用一个音频文件,该文件已使用在线转换器从 mp3 转换为 flac 16000 Hz(如原始代码中指定)。运行代码时出现此错误:

$ python3 speech_api.py 02-29-2016_00-12_msg1.flac 
Traceback (most recent call last):
  File "speech_api.py", line 12, in <module>
    data = f.read()
  File "/usr/lib/python3.4/codecs.py", line 319, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 9: invalid start byte

这是我的代码。 (我确信仍然有一些东西在 Python3 中不起作用,因为我一直在尝试适应它并且对 urllib 很陌生...)

#!/usr/bin/python
import sys
from urllib.request import urlopen
import json
try:
    filename = sys.argv[1]
except IndexError:
    print('Usage: transcribe.py <file>')
    sys.exit(1)

with open(filename) as f:
    data = f.read()

req = urllib.request('https://www.google.com/intl/en/chrome/demos/speech.html', data=data, headers={'Content-type': 'audio/x-flac; rate=16000'})

try:
    ret = urllib.urlopen(req)
except urllib.URLError:
    print("Error Transcribing Voicemail")
    sys.exit(1)

resp = ret.read()
text = json.loads(resp)['hypotheses'][0]['utterance']
print(text)

有什么想法我可以做什么吗?

最佳答案

您需要以二进制模式打开文件:

open(filename, 'wb')

请注意'b',否则文件将被视为文本并解码为 Unicode。

关于python - 声音文件中的 UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724820/

相关文章:

python - 如何仅接受5种可能的输入

python - 从具有匹配词的主列表生成列表,无论顺序如何

python - 在测试和核心之间共享模块 - 适当的项目结构

android - 访问内部存储的媒体文件 - Android 上的 MediaPlayer

audio - 使用来自arduino的串行信息在Processing中播放音频

python - 简单嵌套循环的失败

python - 在2个pandas数据框之间匹配数据并在Python中提取另一列的匹配值

html - html asp.net MVC中的音频currentTime和FileResult

python - Elasticsearch delete_by_query错误用法

python - 如何在 python 3 中找到笛卡尔元素的总和?