语音转文本 - 虚拟物联网设备 在本课程的这一部分中,你将编写代码,使用语音服务将从麦克风捕获的语音转换为文本。 将语音转换为文本 在Windows、Linux和macOS上,可以使用语音服务Python SDK来监听你的麦克风,并将检测到的任何语音转换为文本。它会持续监听,检测音频水平,并在音频水平下降时(例如,一段语音结束时)发送语音以进行文本转换。 任务 - 将语音转换为文本 在计算机上创建一个名为 的文件夹,并在其中创建一个单一文件,命名为 和一个Python虚拟环境。 安装语音服务的Pip包。确保你在终端中激活了虚拟环境后安装该包。 ⚠️ 如果你收到以下错误: > > 你需要更新Pip。通过运行以下命令来更新Pip,然后再次尝试安装该包。
在本课程的这一部分中,你将编写代码,使用语音服务将从麦克风捕获的语音转换为文本。
在Windows、Linux和macOS上,可以使用语音服务Python SDK来监听你的麦克风,并将检测到的任何语音转换为文本。它会持续监听,检测音频水平,并在音频水平下降时(例如,一段语音结束时)发送语音以进行文本转换。
在计算机上创建一个名为 smart-timer 的文件夹,并在其中创建一个单一文件,命名为 app.py 和一个Python虚拟环境。
安装语音服务的Pip包。确保你在终端中激活了虚拟环境后安装该包。
pip install azure-cognitiveservices-speech
⚠️ 如果你收到以下错误:
ERROR: Could not find a version that satisfies the requirement azure-cognitiveservices-speech (from versions: none) ERROR: No matching distribution found for azure-cognitiveservices-speech你需要更新Pip。通过运行以下命令来更新Pip,然后再次尝试安装该包。
pip install --upgrade pip
向 app.py 文件添加以下导入语句:
import requests import time from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer
这些导入语句用于识别语音的一些类。
添加以下代码来声明一些配置:
speech_api_key = '<key>' location = '<location>' language = '<language>' recognizer_config = SpeechConfig(subscription=speech_api_key, region=location, speech_recognition_language=language)
替换 <key> with the API key for your speech service. 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 for Cantonese. You can find a list of the supported languages and their locale names in the Language and voice support documentation on Microsoft docs.
This configuration is then used to create a SpeechConfig 对象,这将用于配置语音服务。
添加以下代码来创建一个语音识别器:
recognizer = SpeechRecognizer(speech_config=recognizer_config)
语音识别器在一个后台线程上运行,监听音频并将其中的语音转换为文本。你可以使用回调函数获取文本——定义一个函数并传递给识别器。每当检测到语音时,都会调用回调函数。添加以下代码来定义一个回调函数,并将其传递给识别器,同时定义一个处理文本的函数,将文本输出到控制台:
def process_text(text): print(text) def recognized(args): process_text(args.result.text) recognizer.recognized.connect(recognized)
识别器只有在显式启动时才会开始监听。添加以下代码来启动识别器。这将在后台运行,因此你的应用程序也需要一个无限循环,以保持应用程序运行。
recognizer.start_continuous_recognition() while True: time.sleep(1)
运行这个应用。对着麦克风说话,音频将被转换为文本并输出到控制台。
(.venv) ➜ smart-timer python3 app.py Hello world. Welcome to IoT for beginners.
尝试不同类型的句子,包括听起来相同但意思不同的词。例如,如果你正在用英语说话,说“我想买两个香蕉和一个苹果”,注意它会根据单词的上下文而不是声音正确地使用to、two和too。
你可以在 code-speech-to-text/virtual-iot-device 文件夹中找到此代码。
你的语音转文本程序成功了!
声明:
本文件灏天文库团队进行了翻译。尽管我们力求准确,但请注意,翻译可能包含错误或不准确之处。原文档以其原始语言为准。我们不对因使用此翻译而产生的任何误解或误译负责。