1
0

my.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import os
  2. import azure.cognitiveservices.speech as speechsdk
  3. import win32clipboard as w
  4. def get_clipboard_text():
  5. w.OpenClipboard()
  6. try:
  7. text = w.GetClipboardData()
  8. except TypeError:
  9. text = ""
  10. w.CloseClipboard()
  11. return text
  12. class SPEECH:
  13. def __init__(self):
  14. # 需要转语音的文本文字
  15. # 设置音频保存本地地址
  16. self.output_file = "r:\\output.wav"
  17. # 从环境变量中获取订阅密钥和区域信息
  18. self.speech_config = speechsdk.SpeechConfig(subscription=os.environ.get('SPEECH_KEY'),
  19. region=os.environ.get('SPEECH_REGION'))
  20. # 设置语音合成使用的语言—— 云枫
  21. self.speech_config.speech_synthesis_language = "zh-CN"
  22. # self.speech_config.speech_synthesis_voice_name = 'zh-CN-YunfengNeural' # 云枫
  23. self.speech_config.speech_synthesis_voice_name = 'zh-CN-XiaoxiaoNeural' # 晓晓
  24. def speak_txt(self):
  25. # 配置音频输出为默认扬声器
  26. audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True)
  27. return audio_config
  28. def down_audio(self):
  29. # 配置音频输出为默认扬声器
  30. audio_config = speechsdk.audio.AudioOutputConfig(filename=self.output_file)
  31. return audio_config
  32. def run(self, text, audio_config):
  33. # 创建语音合成器
  34. speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=self.speech_config, audio_config=audio_config)
  35. # 调用语音合成API将文本转换为语音
  36. speech_synthesis_result = speech_synthesizer.speak_text_async(text).get()
  37. # 检查语音合成的结果并进行相应的处理
  38. if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
  39. print("Speech synthesized for text [{}]".format(text))
  40. elif speech_synthesis_result.reason == speechsdk.ResultReason.Canceled:
  41. cancellation_details = speech_synthesis_result.cancellation_details
  42. print("Speech synthesis canceled: {}".format(cancellation_details.reason))
  43. if cancellation_details.reason == speechsdk.CancellationReason.Error:
  44. if cancellation_details.error_details:
  45. print("Error details: {}".format(cancellation_details.error_details))
  46. print("Did you set the speech resource key and region values?")
  47. if __name__ == "__main__":
  48. my_speech = SPEECH()
  49. # 从剪贴板获取要转换为语音的文本
  50. text = get_clipboard_text()
  51. if not text:
  52. print("剪贴板没有内容,请复制一些文本。")
  53. else:
  54. # 保存到本地
  55. # my_speech.run(text, my_speech.down_audio())
  56. print(text)
  57. # 输出语音播放
  58. my_speech.run(text, my_speech.speak_txt())