pythonV3V4/第11讲语音识别与合成/课堂成果/课后作业-柯南变声领带.py
sairate 2cd753d3d9 feat(第7讲 字母卡牌): 实现记忆游戏并添加开始界面
- 新增 jiyi.py 文件,实现字母翻牌记忆游戏功能
- 添加 youxijiemian.py 文件,创建游戏开始界面
- 使用 turtle 和 tkinter 模块分别实现游戏和界面
- 支持选择不同难度的游戏模式
2025-06-29 09:06:19 +08:00

114 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
》》》运行前必做《《《
1. 运行【安装第三方库.py】文件
2. 注册百度云账号获取API配置后查看完整效果
账号注册指南:
https://huewq7h021.feishu.cn/wiki/Ry3UwaoceiMRXgklbWtc9mEUn9f?from=from_copylink
"""
'''柯南变声领结
任务描述:
变身名侦探柯南,制作一个神奇的变声领结!你将录制一段音频,通过语音识别转换成文字,再通过语音合成器将文字变成机器人音调!快来挑战吧,看谁的变声音效最酷!
作业要求:
1. 将课堂代码【语音识别】和【语音合成】整合到一个文件中
2. 文字合成语音,选择喜欢的“语音人”'''
import pyaudio
import wave
import keyboard
from aip import AipSpeech
# 从麦克风录制音频并保存到指定文件
# 创建 PyAudio 对象
p = pyaudio.PyAudio()
# 打开音频流,设置格式、声道数、采样率等参数
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)
# 创建一个空列表用于存储录制的音频数据
frames = []
# 打印提示信息,表示开始录制
print("Press 's' to start recording...")
# 等待用户按下 's' 键开始录制
keyboard.wait('s')
# 打印提示信息,表示开始录制
print("Recording...")
# 开始录制
while True:
# 从音频流中读取 1024 个数据样本
data = stream.read(1024)
# 将数据添加到 frames 列表中
frames.append(data)
# 检查是否按下 'q' 键结束录制
if keyboard.is_pressed('q'):
break
# 打印提示信息,表示录制已停止
print("Recording stopped.")
# 停止音频流
stream.stop_stream()
# 关闭音频流
stream.close()
# 终止 PyAudio 对象
p.terminate()
# 打开文件,以写入模式打开
wf = wave.open("pyaudio.wav", 'wb')
# 设置音频的声道数、采样宽度和采样率
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(16000)
# 将 frames 列表中的所有数据连接成一个字节串,并写入文件
wf.writeframes(b''.join(frames))
# 关闭文件
wf.close()
print("Done")
# 定义常量
APP_ID = '你的 AppID'
API_KEY = '你的 API Key'
SECRET_KEY = '你的 Secret Key'
# 准备【语音工具】
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# 定义要识别的语音文件
file = 'pyaudio.wav'
# 读取音频文件
def read_audio(file):
with open(file, 'rb') as f:
return f.read()
# 调用语音识别接口
res = client.asr(read_audio(file), 'wav', 16000, {
'dev_pid': 1537 # 普通话识别
})
# 打印返回结果
if 'result' in res:
print("识别结果:", res['result'][0])
else:
print("识别失败:", res)
# 要合成的文本
text = res['result'][0]
# 调用语音合成接口
res = client.synthesis(text, 'zh', 1, {
'vol': 5, # 音量
'per': 0, # 发音人
'spd': 5 # 语速
})
print(res)
# 判断调用是否成功
if not isinstance(res, dict):
# 获取合成音频结果
with open('save.mp3', 'wb') as f:
f.write(res)
print('音频文件保存成功')
else:
print('调用失败, 错误码: %s, 错误信息: %s' % (res['err_no'], res['err_msg']))