语音到文本 - Raspberry Pi 在这节课的这一部分,你将编写代码,使用语音服务将捕获的音频中的语音转换为文本。 将音频发送到语音服务 可以使用REST API将音频发送到语音服务。要使用语音服务,首先需要请求访问令牌,然后使用该令牌访问REST API。这些访问令牌在10分钟后过期,因此你的代码应该定期请求它们以确保它们始终是最新的。 任务 - 获取访问令牌 在你的Pi上打开项目 。 删除 函数。不再需要这个功能,因为你不希望智能计时器重复你说的内容。 在 文件顶部添加以下导入: 在 循环上方添加以下代码,声明一些语音服务的设置: 替换 with the API key for your speech service resource.
在这节课的这一部分,你将编写代码,使用语音服务将捕获的音频中的语音转换为文本。
可以使用REST API将音频发送到语音服务。要使用语音服务,首先需要请求访问令牌,然后使用该令牌访问REST API。这些访问令牌在10分钟后过期,因此你的代码应该定期请求它们以确保它们始终是最新的。
在你的Pi上打开项目smart-timer。
删除play_audio函数。不再需要这个功能,因为你不希望智能计时器重复你说的内容。
在app.py文件顶部添加以下导入:
import requests
在while True循环上方添加以下代码,声明一些语音服务的设置:
speech_api_key = '<key>' location = '<location>' language = '<language>'
替换 <key> with the API key for your speech service resource. Replace <location> with the location you used when you created the speech service resource.
Replace <language> with the locale name for language you will be speaking in, for example en-GB for English, or zn-HK 为粤语。你可以在 Microsoft 文档中的语言和语音支持文档 中找到支持的语言及其区域名称列表。
在此下方,添加以下函数以获取访问令牌:
def get_access_token(): headers = { 'Ocp-Apim-Subscription-Key': speech_api_key } token_endpoint = f'https://{location}.api.cognitive.microsoft.com/sts/v1.0/issuetoken' response = requests.post(token_endpoint, headers=headers) return str(response.text)
这会调用一个颁发令牌的端点,并将API密钥作为头部传递。此调用返回一个可以用来调用语音服务的访问令牌。
在此下方,声明一个函数,使用REST API将捕获的音频中的语音转换为文本:
def convert_speech_to_text(buffer):
在此函数内部,设置REST API的URL和头部:
url = f'https://{location}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1' headers = { 'Authorization': 'Bearer ' + get_access_token(), 'Content-Type': f'audio/wav; codecs=audio/pcm; samplerate={rate}', 'Accept': 'application/json;text/xml' } params = { 'language': language }
使用语音服务资源的位置构建一个URL。然后用从get_access_token函数获取的访问令牌以及用于捕获音频的采样率填充头部。最后定义一些参数,包含音频中的语言。
在此下方,添加以下代码以调用REST API并获取回传的文本:
response = requests.post(url, headers=headers, params=params, data=buffer) response_json = response.json() if response_json['RecognitionStatus'] == 'Success': return response_json['DisplayText'] else: return ''
调用URL并解码响应中包含的JSON值。RecognitionStatus value in the response indicates if the call was able to extract speech into text successfully, and if this is Success then the text is returned from the function, otherwise an empty string is returned.
Above the while True: 循环中,定义一个处理从语音到文本服务返回的文本的函数。目前这个函数只是将文本打印到控制台。
最后,在while True loop with a call to the convert_speech_to_text function, passing the text to the process_text函数中替换对play_audio的调用:
text = convert_speech_to_text(buffer) process_text(text)
运行代码。按住按钮对着麦克风说话。松开按钮后,音频将被转换为文本并打印到控制台。
pi@raspberrypi:~/smart-timer $ python3 app.py Hello world. Welcome to IoT for beginners.
尝试不同类型的句子,包括发音相同但意义不同的句子。例如,如果你使用英语,可以说“我想买两个香蕉和一个苹果”,注意它会根据单词的上下文而不是声音来使用正确的to、two和too。
你可以在code-speech-to-text/pi 文件夹中找到这段代码。
你的语音到文本程序成功了!
声明:
本文件灏天文库团队进行了翻译。尽管我们力求准确,但请注意,翻译可能包含错误或不准确之处。原文档以其原始语言为准。我们不对因使用此翻译而产生的任何误解或误译负责。