from tts_voice import tts_order_voice import edge_tts import gradio as gr import tempfile import anyio import asyncio from edge_tts.exceptions import NoAudioReceived # Import the specific exception # --- Voice Data --- # Uses the dictionary loaded from your tts_voice.py file language_dict = tts_order_voice DEFAULT_LANGUAGE = list(language_dict.keys())[0] # --- Core TTS Function (Asynchronous) --- async def text_to_speech_edge(text, language_code): voice = language_dict[language_code] # Try block to catch the failure try: communicate = edge_tts.Communicate(text, voice) with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: tmp_path = tmp_file.name await communicate.save(tmp_path) return "语音合成完成:{}".format(text), tmp_path except NoAudioReceived as e: error_msg = f"ERROR: Failed to generate audio for voice '{voice}'. The Edge TTS service did not return any audio data. Please try a different voice, use shorter text, or upgrade the 'edge-tts' library. Details: {str(e)}" print(error_msg) # Return the error message and None for audio return error_msg, None except Exception as e: error_msg = f"An unexpected error occurred: {str(e)}" print(error_msg) return error_msg, None # --- Gradio UI Definition --- input_text = gr.Textbox(lines=5, label="输入文本") output_text = gr.Textbox(label="输出文本") output_audio = gr.Audio(type="filepath", label="导出文件") language = gr.Dropdown( choices=list(language_dict.keys()), value=DEFAULT_LANGUAGE, label="语言" ) # --- Gradio Interface Definition and Launch --- # Note: Since the core function is async, we use asyncio for launch interface = gr.Interface( fn=text_to_speech_edge, inputs=[input_text, language], outputs=[output_text, output_audio], title="Edge TTS 文字转语音 (Cloud API)", description="使用微软 Edge TTS 提供的云服务,稳定且无需本地模型加载。" ) if __name__ == "__main__": # Ensure anyio is used to run the async Gradio app anyio.run(interface.launch, backend="asyncio")