微软azure语音生成(澳音)

打开命令行: 按下键盘上的 Win + R 键(Win键就是键盘左下角带微软四个方块图标的键),在弹出的运行小窗口里输入 cmd,然后按回车。

执行安装命令: 在弹出的黑色窗口里,复制并粘贴下面这行命令,然后按回车:

Bashpip install azure-cognitiveservices-speech

等待安装完成: 屏幕上会开始刷出一堆下载进度条。静静等待几十秒,直到最后看到类似于 Successfully installed azure-cognitiveservices-speech... 的绿色或白色字样,就说明安装成功了。

(💡 备用方案:如果你运行上面那行命令报错说找不到 pip,说明你的环境变量没配好。不用慌,换成这行终极命令再回车即可:python -m pip install azure-cognitiveservices-speech)

🐍 交互版终极代码

请用下面这段代码替换你现在的代码(老规矩,别忘了把你的 Key 和 Region 重新填进去):

import os
import sys
import azure.cognitiveservices.speech as speechsdk

def text_to_speech(text, output_file, voice_name):
    # ⚠️ 请务必确保这里换成了你真实的 Key 和 Region
    speech_key = "替换成你的真实_API_KEY"
    service_region = "替换成你的真实_区域代码_例如_eastus"

    try:
        # 获取当前 Python 脚本所在的文件夹路径
        script_dir = os.path.dirname(os.path.abspath(__file__))
        final_output_path = os.path.join(script_dir, output_file)

        # 配置语音服务
        speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
        speech_config.speech_synthesis_voice_name = voice_name
        audio_config = speechsdk.audio.AudioOutputConfig(filename=final_output_path)
        
        speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)

        print(f"正在使用发音人 [{voice_name}] 生成...")
        result = speech_synthesizer.speak_text_async(text).get()

        if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
            print(f"🎉 成功!-> {output_file}")
        elif result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = result.cancellation_details
            print(f"❌ 失败: {cancellation_details.reason}")
                
    except Exception as e:
        print(f"\n🚨 发生致命错误: {e}")

print("==================================")
print("🎙️ PTE 澳音打卡生成器启动!")
print("==================================\n")

# 1. 让程序等待你输入句子
print("👇 请在下方粘贴或输入你今天要跟读的英文句子,然后按【回车键】:")
my_text = input("> ")

print("\n👇 请给这次的音频起个简短的文件名(比如 day2_p1,不需要写 .mp3):")
file_name = input("> ")

print("\n⏳ 正在呼叫微软服务器...\n")

# 2. 根据你输入的文件名,自动生成男声和女声
text_to_speech(my_text, f"{file_name}_Female.mp3", "en-AU-NatashaNeural")
text_to_speech(my_text, f"{file_name}_Male.mp3", "en-AU-WilliamNeural")

print("\n==================================")
input("全部搞定!按【回车键】退出窗口...")

💡 运行效果展示:

当你再次在黑框里拖拽运行这个脚本时,它的表现会非常智能:

  1. 屏幕会提示:请在下方粘贴或输入你今天要跟读的英文句子...
  2. 你把句子 The quick brown fox jumps over the lazy dog. 粘贴进去,按回车。
  3. 屏幕接着问:请给这次的音频起个简短的文件名...
  4. 你输入:voice,按回车。
  5. 唰唰两下,你的 123 文件夹里就会自动多出 voice_Female.mp3voice_Male.mp3 两个文件!

快去更新代码体验一下这种“全自动定制”的快感吧!

🐍支持多段落粘贴的终极代码

我已经把“单行读取”升级成了“多行无限读取”的循环模式。请用下面这段代码替换你现在的代码(最后一次麻烦你把 Key 和 Region 重新填一下啦):

import os
import sys
import azure.cognitiveservices.speech as speechsdk

def text_to_speech(text, output_file, voice_name):
    # ⚠️ 请务必确保这里换成了你真实的 Key 和 Region
    speech_key = "替换成你的真实_API_KEY"
    service_region = "替换成你的真实_区域代码_例如_eastus"

    try:
        # 获取当前 Python 脚本所在的文件夹路径
        script_dir = os.path.dirname(os.path.abspath(__file__))
        final_output_path = os.path.join(script_dir, output_file)

        # 配置语音服务
        speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
        speech_config.speech_synthesis_voice_name = voice_name
        audio_config = speechsdk.audio.AudioOutputConfig(filename=final_output_path)
        
        speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)

        print(f"正在使用发音人 [{voice_name}] 生成...")
        result = speech_synthesizer.speak_text_async(text).get()

        if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
            print(f"🎉 成功!-> {output_file}")
        elif result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = result.cancellation_details
            print(f"❌ 失败: {cancellation_details.reason}")
                
    except Exception as e:
        print(f"\n🚨 发生致命错误: {e}")

print("==================================")
print("🎙️ PTE 澳音打卡生成器启动!")
print("==================================\n")

# 1. 开启多行输入模式
print("👇 请在下方粘贴你想跟读的【多段落英文】。")
print("⚠️ 粘贴完成后,请在【新的一行】输入 END 并按【回车键】确认:\n")

lines = []
while True:
    line = input()
    # 当检测到新的一行单独输入了 END 时,停止接收
    if line.strip() == "END":
        break
    lines.append(line)

# 将接收到的多行文本重新拼接成一段完整的话,中间保留换行
my_text = "\n".join(lines)

print("\n👇 请给这次的音频起个简短的文件名(比如 day3,不需要写 .mp3):")
file_name = input("> ")

print("\n⏳ 正在呼叫微软服务器...\n")

# 2. 根据你输入的文件名,自动生成男声和女声
text_to_speech(my_text, f"{file_name}_Female.mp3", "en-AU-NatashaNeural")
text_to_speech(my_text, f"{file_name}_Male.mp3", "en-AU-WilliamNeural")

print("\n==================================")
input("全部搞定!按【回车键】退出窗口...")

💡 现在你会体验到这样的丝滑操作:

  1. 运行脚本,它会提示你粘贴长篇英文。
  2. 你随意粘贴一整篇文章,无论里面有多少个空行或换行,它都会全部默默收下。
  3. 粘贴完之后,你在最底下的新行里敲入 END 这三个大写字母,然后按下回车。
  4. 程序心领神会,立刻开始打包这整段长文本发送给微软服务器。

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部