用脚本转换文本为语音怎么做

wen 实用脚本 1

本文目录导读:

用脚本转换文本为语音怎么做

  1. Python + pyttsx3(离线,免费)
  2. Python + gTTS(谷歌在线服务)
  3. Python + edge-tts(微软在线服务)- 推荐
  4. Bash 脚本方案
  5. Node.js 脚本方案
  6. 快速安装指南
  7. 实际示例:批量转换文本
  8. 推荐选择

Python + pyttsx3(离线,免费)

import pyttsx3
# 初始化
engine = pyttsx3.init()
# 设置语音属性
engine.setProperty('rate', 150)    # 语速
engine.setProperty('volume', 0.9)  # 音量
# 获取可用语音
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)  # 选择第一个语音
# 转换文本为语音
text = "你好,欢迎使用文本转语音功能!"
engine.say(text)
# 保存为音频文件
engine.save_to_file(text, 'output.mp3')
engine.runAndWait()

Python + gTTS(谷歌在线服务)

from gtts import gTTS
import os
# 文本转语音
text = "Hello, this is a text to speech example!"
tts = gTTS(text=text, lang='en')  # lang='zh-cn' 为中文
# 保存音频文件
tts.save("output.mp3")
# 播放(Linux)
os.system("mpg321 output.mp3")  # 或其他播放命令

Python + edge-tts(微软在线服务)- 推荐

import asyncio
import edge_tts
async def text_to_speech():
    text = "这是一个文本转语音的示例"
    # 创建语音对象
    tts = edge_tts.Communicate(text, "zh-CN-XiaoxiaoNeural")
    # 保存为文件
    await tts.save("output.mp3")
    # 流式获取音频数据
    audio_data = b""
    async for chunk in tts.stream():
        if chunk["type"] == "audio":
            audio_data += chunk["data"]
asyncio.run(text_to_speech())

Bash 脚本方案

#!/bin/bash
# 使用 espeak(Linux)
echo "Hello World" | espeak
# 使用 festival(Linux)
echo "Hello World" | festival --tts
# 使用 say(macOS)
say "Hello World" -o output.aiff

Node.js 脚本方案

// 使用第三方库
const gtts = require('node-gtts')('zh');
const fs = require('fs');
gtts.save('output.mp3', '你好,世界!', function() {
    console.log('转换完成!');
});

快速安装指南

根据不同方案,安装相应依赖:

# Python 方案
pip install pyttsx3 gtts edge-tts
# Node.js 方案
npm install node-gtts
# Linux 语音工具
sudo apt-get install espeak festival mpg321

实际示例:批量转换文本

# 批量转换文本文件
import edge_tts
import asyncio
async def batch_conversion():
    # 读取文本文件
    with open('input.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
    # 逐行转换
    for i, line in enumerate(lines):
        if line.strip():
            tts = edge_tts.Communicate(line.strip(), "zh-CN-XiaoxiaoNeural")
            await tts.save(f"output_{i}.mp3")
            print(f"已生成第{i+1}段音频")
asyncio.run(batch_conversion())

推荐选择

  1. 简单快速:使用 gTTS(需要网络)
  2. 离线可用:pyttsx3
  3. 语音质量最高:edge-tts(微软神经语音)
  4. Linux服务器:espeak

选择哪个方案取决于你的具体需求,比如是否需要离线、语音质量要求、平台限制等,需要我详细解释某个方案吗?

抱歉,评论功能暂时关闭!