Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import torch | |
| # 使用 voxcpm 库中专属的类 | |
| from voxcpm import VoxCPM, VoxCPMFeatureExtractor | |
| import scipy.io.wavfile | |
| import os | |
| # 检查是否有可用的 GPU,否则使用 CPU | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| # 模型 ID | |
| model_id = "openbmb/VoxCPM-0.5B" | |
| # 使用模型官方的 .from_pretrained 方法加载 | |
| model = VoxCPM.from_pretrained(model_id).to(device) | |
| feature_extractor = VoxCPMFeatureExtractor.from_pretrained(model_id) | |
| def generate_speech(text): | |
| """ | |
| 使用 VoxCPM 模型生成语音的函数。 | |
| """ | |
| if not text or text.strip() == "": | |
| return None | |
| # 使用模型自带的 generate 方法生成语音波形 | |
| wav = model.generate( | |
| text=text, | |
| prompt_wav_path=None, | |
| prompt_text=None, | |
| cfg_value=2.0 | |
| ) | |
| # 从 feature_extractor 获取采样率 | |
| sampling_rate = feature_extractor.sampling_rate | |
| # 确保波形数据是 CPU 上的 numpy 数组 | |
| if isinstance(wav, torch.Tensor): | |
| wav = wav.cpu().numpy() | |
| # 将生成的波形保存为临时的 .wav 文件 | |
| output_filename = "output.wav" | |
| scipy.io.wavfile.write(output_filename, rate=sampling_rate, data=wav) | |
| return output_filename | |
| # 创建 Gradio 界面 | |
| iface = gr.Interface( | |
| fn=generate_speech, | |
| inputs=gr.Textbox(lines=5, label="输入文本", placeholder="在这里输入你想要转换为语音的中文或英文文本..."), | |
| outputs=gr.Audio(label="生成的语音"), | |
| title="🎙️ VoxCPM-0.5B 文本到语音转换", | |
| description="这是一个使用 openbmb/VoxCPM-0.5B 模型进行文本到语音合成的演示。", | |
| examples=[ | |
| ["VoxCPM 是一个创新的端到端 TTS 模型,旨在生成高度富有表现力的语音。"], | |
| ["今天天气真不错,我们一起去散步吧!"], | |
| ["The quick brown fox jumps over the lazy dog."] | |
| ], | |
| allow_flagging="never" | |
| ) | |
| # 启动 Gradio 应用 | |
| iface.launch() |