不使用SpeechRecognition库,换一种方式
时间: 2023-05-28 17:05:24 浏览: 97
如果不使用SpeechRecognition库,可以使用Python的PyAudio库来录制音频并使用Google的语音识别API进行语音识别。以下是一个简单的示例代码:
```python
import pyaudio
import wave
import requests
# 录音配置
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 5
# 录制音频
audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
print("开始录音...")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("录音结束")
stream.stop_stream()
stream.close()
audio.terminate()
# 将音频保存为WAV文件
wf = wave.open("audio.wav", "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
wf.close()
# 语音识别
url = "https://speech.googleapis.com/v1/speech:recognize?key=YOUR_API_KEY"
headers = {"Content-Type": "application/json"}
data = {
"config": {
"encoding": "LINEAR16",
"sampleRateHertz": RATE,
"languageCode": "en-US",
},
"audio": {
"content": open("audio.wav", "rb").read().encode("base64"),
},
}
response = requests.post(url, headers=headers, json=data)
transcript = response.json()["results"][0]["alternatives"][0]["transcript"]
print("识别结果:", transcript)
```
需要将`YOUR_API_KEY`替换为你自己的Google语音识别API密钥。此外,该示例代码只适用于英语语音识别,如果需要识别其他语言,需要修改语言代码。
阅读全文