a
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
# TTS Streamer - 多语言文本转音频流
|
||||
|
||||
实时将文本转换为音频,通过 HTTP 流媒体远程收听。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- ✅ **多语言支持**:中文、英文、日文
|
||||
- ✅ **流式播放**:边转换边播放,无需等待
|
||||
- ✅ **远程收听**:浏览器或播放器直接访问 URL
|
||||
- ✅ **批量转换**:支持文件夹批量处理
|
||||
- ✅ **轻量简洁**:基于 edge-tts,免费高质量
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 安装依赖
|
||||
|
||||
```bash
|
||||
# Python 3.8+
|
||||
pip install edge-tts
|
||||
|
||||
# 可选:HTTP 服务器
|
||||
pip install flask
|
||||
```
|
||||
|
||||
### 2. 测试转换
|
||||
|
||||
```bash
|
||||
# 英文
|
||||
python scripts/tts_convert.py articles/hello_en.txt --lang en
|
||||
|
||||
# 中文
|
||||
python scripts/tts_convert.py articles/hello_zh.txt --lang zh
|
||||
|
||||
# 日文
|
||||
python scripts/tts_convert.py articles/hello_jp.txt --lang jp
|
||||
```
|
||||
|
||||
### 3. 启动流服务
|
||||
|
||||
```bash
|
||||
# 单文件流式播放
|
||||
python scripts/stream_server.py articles/hello_en.txt --port 8080
|
||||
|
||||
# 然后在浏览器或播放器打开:
|
||||
# http://你的IP:8080/stream
|
||||
```
|
||||
|
||||
## 语言代码
|
||||
|
||||
| 语言 | 代码 | 默认语音 |
|
||||
|------|------|---------|
|
||||
| 中文 | `zh` | 晓晓 (Xiaoxiao) |
|
||||
| 英文 | `en` | Aria |
|
||||
| 日文 | `jp` | Nanami |
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
tts-streamer/
|
||||
├── README.md
|
||||
├── articles/ # 放文本文件
|
||||
├── output/ # 输出音频文件
|
||||
├── scripts/ # 工具脚本
|
||||
│ ├── tts_convert.py # 转换脚本
|
||||
│ ├── stream_server.py # 流服务
|
||||
│ └── batch_convert.py # 批量转换
|
||||
└── web/ # Web 控制界面
|
||||
```
|
||||
|
||||
## 高级用法
|
||||
|
||||
### 批量转换
|
||||
|
||||
```bash
|
||||
python scripts/batch_convert.py articles/ --output output/
|
||||
```
|
||||
|
||||
### 内网穿透(无公网 IP)
|
||||
|
||||
```bash
|
||||
# 使用 cloudflare tunnel
|
||||
cloudflared tunnel --url http://localhost:8080
|
||||
```
|
||||
|
||||
## 依赖
|
||||
|
||||
- Python 3.8+
|
||||
- edge-tts (微软 Edge 语音)
|
||||
- flask (可选,用于 Web 控制)
|
||||
@@ -0,0 +1,13 @@
|
||||
Hello and welcome to this English learning session.
|
||||
|
||||
Today, we will practice some common phrases that you can use in daily conversations.
|
||||
|
||||
First, let's start with greetings. When you meet someone in the morning, you can say "Good morning!" In the afternoon, use "Good afternoon!" And in the evening, say "Good evening!"
|
||||
|
||||
When you want to introduce yourself, you can say: "Hello, my name is... Nice to meet you!"
|
||||
|
||||
If you need help, don't hesitate to ask: "Excuse me, could you please help me?"
|
||||
|
||||
To express gratitude, simply say "Thank you very much" or "I really appreciate your help."
|
||||
|
||||
Practice these phrases daily, and your English will improve quickly!
|
||||
@@ -0,0 +1,13 @@
|
||||
こんにちは。日本語学習へようこそ。
|
||||
|
||||
今日は、日常会話で使える基本的なフレーズを練習します。
|
||||
|
||||
まず、あいさつから始めましょう。朝は「おはようございます」、昼は「こんにちは」、夜は「こんばんは」と言います。
|
||||
|
||||
自分を紹介する時は「初めまして、私は...です。よろしくお願いします」と言います。
|
||||
|
||||
助けが必要な時は「すみません、手伝っていただけますか」と尋ねます。
|
||||
|
||||
感謝を表す時は「ありがとうございます」または「どうもありがとう」と言います。
|
||||
|
||||
毎日これらのフレーズを練習すれば、日本語はきっと上達します!
|
||||
@@ -0,0 +1,13 @@
|
||||
你好,欢迎收听中文学习内容。
|
||||
|
||||
今天,我们将练习一些日常生活中常用的中文短语。
|
||||
|
||||
首先,让我们从问候开始。早上见到别人时,你可以说"早上好!"下午可以说"下午好!"晚上则说"晚上好!"
|
||||
|
||||
当你想介绍自己时,可以说:"你好,我叫...很高兴认识你!"
|
||||
|
||||
如果你需要帮助,可以礼貌地问:"不好意思,请问你能帮我一下吗?"
|
||||
|
||||
表达感谢时,简单说"非常感谢"或"谢谢你的帮助"就可以了。
|
||||
|
||||
每天练习这些短语,你的中文会很快进步的!
|
||||
@@ -0,0 +1,13 @@
|
||||
中文学习文章:坚持的力量
|
||||
|
||||
学习一门新语言,就像培养一个习惯。每天坚持,就能看见进步。
|
||||
|
||||
很多人问:"怎样才能快速提高中文水平?"答案其实很简单:持之以恒。每天学习十五分钟,比一天突击学习三小时更有效。
|
||||
|
||||
从小目标开始。每天读一篇短文。上下班路上听听中文播客。睡前用中文写三句话,记录今天发生的事情。
|
||||
|
||||
不要害怕犯错。每一个错误都是学习的机会。母语者会欣赏你努力交流的心意,即使你的语法还不够完美。
|
||||
|
||||
记住:目标是进步,而不是完美。坚持练习,你会比想象中更快看到成果。
|
||||
|
||||
这篇文章旨在帮助中文学习者通过每日练习提高听力。建议多次收听,熟悉自然的中文语调和节奏。
|
||||
@@ -0,0 +1,13 @@
|
||||
English Learning Article: The Power of Daily Practice
|
||||
|
||||
Learning a new language is like building a muscle. The more you practice, the stronger you become.
|
||||
|
||||
Many people ask: "How can I improve my English quickly?" The answer is surprisingly simple: consistency. Just fifteen minutes of practice every day is better than three hours once a week.
|
||||
|
||||
Start with small steps. Read one short article daily. Listen to a podcast during your commute. Write three sentences about your day before sleeping.
|
||||
|
||||
Don't worry about making mistakes. Every error is a learning opportunity. Native speakers appreciate your effort to communicate, even if your grammar isn't perfect.
|
||||
|
||||
Remember: Progress, not perfection, is the goal. Keep practicing, and you will see results sooner than you expect.
|
||||
|
||||
This article is designed to help English learners improve their listening skills through daily practice. Listen to this recording multiple times to familiarize yourself with natural English pronunciation and rhythm.
|
||||
@@ -0,0 +1,13 @@
|
||||
日本語学習記事:毎日の練習の力
|
||||
|
||||
新しい言語を学ぶことは、筋肉を鍛えるようなものです。練習を重ねるほど、強くなっていきます。
|
||||
|
||||
多くの人が尋ねます:「どうやれば日本語が早く上達しますか?」答えは驚くほど簡単です:一貫性です。週に一度三時間やるより、毎日十五分練習する方が良いのです。
|
||||
|
||||
小さな一歩から始めましょう。毎日短い記事を一つ読む。通勤中にポッドキャストを聴く。寝る前に、今日のことを三つ文で書く。
|
||||
|
||||
間違いを恐れないでください。一つ一つの間違いは学習の機会です。文法が完璧でなくても、あなたがコミュニケーションを取ろうとする努力を、ネイティブスピーカーは評価してくれます。
|
||||
|
||||
覚えておいてください:目標は完璧さではなく、進歩です。練習を続ければ、思っているより早く結果が現れます。
|
||||
|
||||
この記事は、日本語学習者が毎日の練習を通じてリスニングスキルを向上させることを目的としています。自然な日本語の発音とリズムに慣れるために、この録音を何度も聴いてください。
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
+70
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
批量转换脚本 - 转换整个文件夹
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from tts_convert import convert_file, VOICES
|
||||
|
||||
|
||||
async def batch_convert(input_dir: str, output_dir: str, lang: str = 'auto'):
|
||||
"""批量转换文件夹"""
|
||||
input_path = Path(input_dir)
|
||||
output_path = Path(output_dir)
|
||||
|
||||
if not input_path.exists():
|
||||
print(f"❌ 输入目录不存在: {input_dir}")
|
||||
return
|
||||
|
||||
# 创建输出目录
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 查找所有文本文件
|
||||
text_files = list(input_path.glob('*.txt')) + list(input_path.glob('*.md'))
|
||||
|
||||
if not text_files:
|
||||
print(f"⚠️ 未找到文本文件: {input_dir}")
|
||||
return
|
||||
|
||||
print(f"📝 找到 {len(text_files)} 个文件")
|
||||
print('=' * 60)
|
||||
|
||||
# 逐个转换
|
||||
success = 0
|
||||
failed = 0
|
||||
|
||||
for i, file in enumerate(text_files, 1):
|
||||
output_file = output_path / file.with_suffix('.mp3').name
|
||||
|
||||
print(f"\n[{i}/{len(text_files)}] {file.name}")
|
||||
|
||||
try:
|
||||
await convert_file(str(file), lang, str(output_file))
|
||||
success += 1
|
||||
except Exception as e:
|
||||
print(f"❌ 失败: {e}")
|
||||
failed += 1
|
||||
|
||||
print('\n' + '=' * 60)
|
||||
print(f"✅ 完成: {success} 成功, {failed} 失败")
|
||||
print(f"📁 输出目录: {output_path.absolute()}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='批量 TTS 转换')
|
||||
parser.add_argument('input_dir', help='输入文件夹')
|
||||
parser.add_argument('--output', '-o', default='output', help='输出文件夹')
|
||||
parser.add_argument('--lang', '-l', default='auto',
|
||||
choices=['auto', 'zh', 'zh-hk', 'en', 'en-gb', 'jp', 'kr'],
|
||||
help='语言代码')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
asyncio.run(batch_convert(args.input_dir, args.output, args.lang))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+142
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
流式 TTS 服务器 - 实时音频流
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import argparse
|
||||
import edge_tts
|
||||
from pathlib import Path
|
||||
from flask import Flask, Response, send_file
|
||||
import threading
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# 全局配置
|
||||
VOICES = {
|
||||
'zh': 'zh-CN-XiaoxiaoNeural',
|
||||
'zh-hk': 'zh-HK-HiuMaanNeural',
|
||||
'en': 'en-US-AriaNeural',
|
||||
'en-gb': 'en-GB-SoniaNeural',
|
||||
'jp': 'ja-JP-NanamiNeural',
|
||||
'kr': 'ko-KR-SunHiNeural',
|
||||
}
|
||||
|
||||
DEFAULT_TEXT = """
|
||||
Welcome to TTS Streamer. This is a test message.
|
||||
欢迎使用文本转音频流服务。这是测试消息。
|
||||
"""
|
||||
|
||||
|
||||
def detect_language(text: str) -> str:
|
||||
"""检测语言"""
|
||||
if any('\u3040' <= c <= '\u309f' or '\u30a0' <= c <= '\u30ff' for c in text[:100]):
|
||||
return 'jp'
|
||||
if any('\uac00' <= c <= '\ud7af' for c in text[:100]):
|
||||
return 'kr'
|
||||
if any('\u4e00' <= c <= '\u9fff' for c in text[:100]):
|
||||
return 'zh'
|
||||
return 'en'
|
||||
|
||||
|
||||
async def generate_audio_stream(text: str, voice_code: str = 'auto'):
|
||||
"""生成音频流"""
|
||||
if voice_code == 'auto':
|
||||
voice_code = detect_language(text)
|
||||
|
||||
voice = VOICES.get(voice_code, VOICES['zh'])
|
||||
communicate = edge_tts.Communicate(text, voice)
|
||||
|
||||
async for chunk in communicate.stream():
|
||||
if chunk["type"] == "audio":
|
||||
yield chunk["data"]
|
||||
|
||||
|
||||
def run_async_stream(text: str, voice_code: str):
|
||||
"""在同步上下文中运行异步流"""
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
async def stream_generator():
|
||||
async for chunk in generate_audio_stream(text, voice_code):
|
||||
yield chunk
|
||||
|
||||
# 转换为同步生成器
|
||||
gen = stream_generator()
|
||||
while True:
|
||||
try:
|
||||
chunk = loop.run_until_complete(gen.__anext__())
|
||||
yield chunk
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
|
||||
|
||||
@app.route('/stream')
|
||||
def stream_audio():
|
||||
"""音频流端点"""
|
||||
text = app.config.get('TEXT', DEFAULT_TEXT)
|
||||
voice = app.config.get('VOICE', 'auto')
|
||||
|
||||
return Response(
|
||||
run_async_stream(text, voice),
|
||||
mimetype='audio/mpeg',
|
||||
headers={
|
||||
'Content-Type': 'audio/mpeg',
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Cache-Control': 'no-cache'
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
"""首页"""
|
||||
text = app.config.get('TEXT', DEFAULT_TEXT)[:200]
|
||||
return f"""
|
||||
<h1>🔊 TTS Streamer</h1>
|
||||
<p>当前文本: {text}...</p>
|
||||
<p>点击播放: <a href="/stream">/stream</a></p>
|
||||
<hr>
|
||||
<p>或使用播放器直接打开: http://服务器IP:端口/stream</p>
|
||||
"""
|
||||
|
||||
|
||||
def serve_file(input_file: str, port: int = 8080, voice: str = 'auto'):
|
||||
"""提供文件流服务"""
|
||||
# 读取文件
|
||||
path = Path(input_file)
|
||||
if not path.exists():
|
||||
print(f"❌ 文件不存在: {input_file}")
|
||||
return
|
||||
|
||||
with open(input_file, 'r', encoding='utf-8') as f:
|
||||
text = f.read()
|
||||
|
||||
# 配置
|
||||
app.config['TEXT'] = text
|
||||
app.config['VOICE'] = voice
|
||||
|
||||
print(f"🎙️ 准备播放: {input_file}")
|
||||
print(f"🌐 访问地址:")
|
||||
print(f" http://0.0.0.0:{port}/stream")
|
||||
print(f" http://0.0.0.0:{port}/ (网页)")
|
||||
print(f"\n📝 语言: {detect_language(text)}")
|
||||
print("按 Ctrl+C 停止服务")
|
||||
|
||||
# 启动服务
|
||||
app.run(host='0.0.0.0', port=port, threaded=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='TTS 流服务器')
|
||||
parser.add_argument('input', help='输入文本文件')
|
||||
parser.add_argument('--port', '-p', type=int, default=8080, help='端口 (默认: 8080)')
|
||||
parser.add_argument('--voice', '-v', default='auto', help='语音代码')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
serve_file(args.input, args.port, args.voice)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+106
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
TTS 转换脚本 - 支持多语言
|
||||
支持:中文(zh)、英文(en)、日文(jp)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import edge_tts
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 语音配置
|
||||
VOICES = {
|
||||
'zh': 'zh-CN-XiaoxiaoNeural', # 中文-晓晓
|
||||
'zh-hk': 'zh-HK-HiuMaanNeural', # 粤语
|
||||
'en': 'en-US-AriaNeural', # 英语-美音
|
||||
'en-gb': 'en-GB-SoniaNeural', # 英语-英音
|
||||
'jp': 'ja-JP-NanamiNeural', # 日语
|
||||
'kr': 'ko-KR-SunHiNeural', # 韩语
|
||||
}
|
||||
|
||||
# 默认语速
|
||||
DEFAULT_RATE = "+0%"
|
||||
|
||||
|
||||
async def convert_text_to_speech(text: str, voice: str, output_file: str, rate: str = DEFAULT_RATE):
|
||||
"""将文本转换为语音"""
|
||||
communicate = edge_tts.Communicate(text, voice, rate=rate)
|
||||
await communicate.save(output_file)
|
||||
print(f"✅ 已保存: {output_file}")
|
||||
|
||||
|
||||
async def convert_file(input_file: str, lang: str = 'auto', output_file: str = None, rate: str = DEFAULT_RATE):
|
||||
"""转换文件"""
|
||||
input_path = Path(input_file)
|
||||
|
||||
if not input_path.exists():
|
||||
print(f"❌ 文件不存在: {input_file}")
|
||||
sys.exit(1)
|
||||
|
||||
# 读取文本
|
||||
with open(input_file, 'r', encoding='utf-8') as f:
|
||||
text = f.read()
|
||||
|
||||
# 自动检测语言(简单判断)
|
||||
if lang == 'auto':
|
||||
lang = detect_language(text)
|
||||
print(f"🔍 检测到语言: {lang}")
|
||||
|
||||
# 获取语音
|
||||
voice = VOICES.get(lang, VOICES['zh'])
|
||||
|
||||
# 确定输出文件名
|
||||
if output_file is None:
|
||||
output_file = str(input_path.with_suffix('.mp3'))
|
||||
|
||||
# 转换
|
||||
print(f"🎙️ 使用语音: {voice}")
|
||||
print(f"📝 转换: {input_file} -> {output_file}")
|
||||
await convert_text_to_speech(text, voice, output_file, rate)
|
||||
|
||||
return output_file
|
||||
|
||||
|
||||
def detect_language(text: str) -> str:
|
||||
"""简单语言检测"""
|
||||
# 日文假名
|
||||
if any('\u3040' <= c <= '\u309f' or '\u30a0' <= c <= '\u30ff' for c in text[:100]):
|
||||
return 'jp'
|
||||
# 韩文
|
||||
if any('\uac00' <= c <= '\ud7af' for c in text[:100]):
|
||||
return 'kr'
|
||||
# 中文
|
||||
if any('\u4e00' <= c <= '\u9fff' for c in text[:100]):
|
||||
return 'zh'
|
||||
# 默认英文
|
||||
return 'en'
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='文本转语音工具')
|
||||
parser.add_argument('input', help='输入文本文件')
|
||||
parser.add_argument('--lang', '-l', default='auto',
|
||||
choices=['auto', 'zh', 'zh-hk', 'en', 'en-gb', 'jp', 'kr'],
|
||||
help='语言代码 (默认: auto)')
|
||||
parser.add_argument('--output', '-o', help='输出音频文件')
|
||||
parser.add_argument('--rate', '-r', default=DEFAULT_RATE,
|
||||
help='语速调整,如 "+10%" 或 "-10%"')
|
||||
parser.add_argument('--list-voices', action='store_true',
|
||||
help='列出所有可用语音')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.list_voices:
|
||||
print("可用语音:")
|
||||
for code, voice in VOICES.items():
|
||||
print(f" {code}: {voice}")
|
||||
return
|
||||
|
||||
# 运行转换
|
||||
asyncio.run(convert_file(args.input, args.lang, args.output, args.rate))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
# TTS Streamer 快速启动脚本
|
||||
|
||||
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
show_help() {
|
||||
echo "🎙️ TTS Streamer - 文本转音频流"
|
||||
echo ""
|
||||
echo "用法:"
|
||||
echo " ./start.sh convert <文件> [语言] # 转换单个文件"
|
||||
echo " ./start.sh stream <文件> [端口] # 启动流服务"
|
||||
echo " ./start.sh batch [文件夹] # 批量转换"
|
||||
echo " ./start.sh test # 测试所有语言"
|
||||
echo ""
|
||||
echo "语言代码: zh(中文) en(英文) jp(日文)"
|
||||
echo ""
|
||||
echo "示例:"
|
||||
echo " ./start.sh convert articles/hello_en.txt en"
|
||||
echo " ./start.sh stream articles/hello_zh.txt 8080"
|
||||
}
|
||||
|
||||
case "${1:-help}" in
|
||||
convert)
|
||||
FILE="${2:-articles/hello_en.txt}"
|
||||
LANG="${3:-auto}"
|
||||
python3 scripts/tts_convert.py "$FILE" --lang "$LANG"
|
||||
;;
|
||||
|
||||
stream)
|
||||
FILE="${2:-articles/hello_en.txt}"
|
||||
PORT="${3:-8080}"
|
||||
echo "🌐 启动流服务: $FILE"
|
||||
echo "📱 访问: http://$(hostname -I | awk '{print $1}' 2>/dev/null || echo 'localhost'):$PORT/stream"
|
||||
echo ""
|
||||
python3 scripts/stream_server.py "$FILE" --port "$PORT"
|
||||
;;
|
||||
|
||||
batch)
|
||||
DIR="${2:-articles/}"
|
||||
python3 scripts/batch_convert.py "$DIR" --output output/
|
||||
;;
|
||||
|
||||
test)
|
||||
echo "🧪 测试多语言转换..."
|
||||
for file in articles/hello_*.txt; do
|
||||
echo ""
|
||||
echo "📝 转换: $file"
|
||||
python3 scripts/tts_convert.py "$file"
|
||||
done
|
||||
echo ""
|
||||
echo "✅ 测试完成,文件保存在 output/"
|
||||
;;
|
||||
|
||||
help|--help|-h)
|
||||
show_help
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "❌ 未知命令: $1"
|
||||
show_help
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
Reference in New Issue
Block a user