首先需要安装pyaudio第三库
然后获取您的阿里云DashScope API密钥,并在代码中设置
导包:
import pyaudio
from dashscope.audio.asr import Recognition, RecognitionCallback, RecognitionResult
设密钥:
dashscope.api_key = 'YOUR-DASHSCOPE-API-KEY' # 使用您的API密钥替换此处
回调类:
class Callback(RecognitionCallback):
def on_open(self) -> None:
global mic, stream
print('RecognitionCallback open.')
mic = pyaudio.PyAudio()
stream = mic.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
def on_close(self) -> None:
global mic, stream
print('RecognitionCallback close.')
stream.stop_stream()
stream.close()
mic.terminate()
stream = None
mic = None
def on_event(self, result: RecognitionResult) -> None:
print('RecognitionCallback sentence: ', result.get_sentence())
然后说初始化:callback = Callback()
recognition = Recognition(model='paraformer-realtime-v2', format='pcm', sample_rate=16000, callback=callback)
recognition.start()
while True:
if stream:
data = stream.read(3200, exception_on_overflow=False)
recognition.send_audio_frame(data)
else:
break
recognition.stop()
[
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。