This commit is contained in:
Ubuntu
2026-07-03 16:58:28 +08:00
commit 32b43f85bd
6240 changed files with 1987678 additions and 0 deletions
+101
View File
@@ -0,0 +1,101 @@
# 📚 Audiobook Player
极简沉浸式的英文有声书 Web 应用。
## ✨ Features
- 🎨 **极简设计** - 米白底色,纸质书阅读体验
- 🌙 **夜间模式** - 一键切换深色主题
- 📱 **移动优先** - 完美适配手机,支持 App 内嵌浏览器
- 🔊 **流式朗读** - 实时 TTS,无需等待完整转换
- 🔄 **断点续读** - 自动保存阅读进度
- ⚡ **懒加载** - 长文章分段加载,流畅滑动
- 👆 **手势支持** - 滑动返回,双击缩放
## 🏗️ 架构
```
Flask Backend Frontend
├── / (index) ────────▶ 首页(来源选择)
├── /list/<source> ────────▶ 故事列表
├── /play/<path> ────────▶ 播放页面
│ ├─ 顶部固定播放器
│ └─ 下方内容区
└── /api/stream ────────▶ TTS 音频流
```
## 🚀 快速开始
```bash
cd ~/nanocode/audiobook-player
# 安装依赖
pip3 install -r requirements.txt
# 启动服务器
./start.sh start-bg
# 查看状态
./start.sh status
```
访问:http://localhost:5000
## 📁 目录结构
```
/home/ubuntu/media/
├── libraryofshortstories/
│ ├── the-1000000-bank-note/
│ │ ├── content.txt
│ │ └── metadata.md
│ └── ...
└── public-domain-poetry/
└── ...
```
## 🎮 页面导航
| 页面 | 路径 | 功能 |
|------|------|------|
| 首页 | `/` | 显示所有来源(libraryofshortstories, poetry等) |
| 列表 | `/list/<source>` | 该来源下的故事列表 |
| 播放 | `/play/<source>/<story>` | 播放器 + 文章内容 |
## 🎨 设计规范
- **配色**:米白 `#F5F1E8` / 深黑 `#1A1A1A`
- **字体**:Georgia 衬线体
- **播放器**:固定 100px,磨砂玻璃效果
- **卡片**:圆角 16px,阴影
- **触摸区**:≥ 80px
## 🔧 开发计划
- [x] 基础 Flask 框架
- [x] 三页面模板
- [x] 流式 TTS 播放
- [x] 主题切换
- [ ] 阅读进度同步
- [ ] 播放速度调节
- [ ] 收藏功能
## 📱 App 集成
适合嵌入手机 App 的 WebView:
```swift
// iOS WKWebView
let webView = WKWebView()
webView.load(URLRequest(url: URL(string: "http://129.211.173.87:5000")!))
```
```kotlin
// Android WebView
webView.loadUrl("http://129.211.173.87:5000")
```
特点:
- 每页独立返回按钮,不依赖浏览器导航
- 无地址栏干扰
- 响应式布局
+271
View File
@@ -0,0 +1,271 @@
# 📚 Audiobook Player 使用说明
> 极简沉浸式有声书 Web 应用
---
## 🌐 访问地址
```
http://129.211.173.87:8899
```
---
## 🚀 服务管理
### 使用 Systemd 管理(推荐)
```bash
# 启动服务
sudo systemctl start audiobook-player
# 停止服务
sudo systemctl stop audiobook-player
# 重启服务
sudo systemctl restart audiobook-player
# 查看状态
sudo systemctl status audiobook-player
# 设置开机自启
sudo systemctl enable audiobook-player
# 取消开机自启
sudo systemctl disable audiobook-player
```
### 查看日志
```bash
# 实时日志
sudo journalctl -u audiobook-player -f
# 最近 100 行
sudo journalctl -u audiobook-player -n 100
```
---
## 🛠️ 安装/卸载服务
### 安装服务(首次使用)
```bash
cd ~/nanocode/audiobook-player
# 1. 复制服务文件到系统目录
sudo cp audiobook-player.service /etc/systemd/system/
# 2. 重新加载 systemd
sudo systemctl daemon-reload
# 3. 启动服务
sudo systemctl start audiobook-player
# 4. 设置开机自启(可选)
sudo systemctl enable audiobook-player
# 5. 检查状态
sudo systemctl status audiobook-player
```
### 卸载服务
```bash
# 1. 停止并禁用
sudo systemctl stop audiobook-player
sudo systemctl disable audiobook-player
# 2. 删除服务文件
sudo rm /etc/systemd/system/audiobook-player.service
# 3. 重新加载
sudo systemctl daemon-reload
```
---
## 📂 项目结构
```
~/nanocode/audiobook-player/
├── app.py # Flask 主程序
├── audiobook-player.service # Systemd 服务配置
├── requirements.txt # Python 依赖
├── USAGE.md # 本文档
├── templates/ # HTML 模板
│ ├── index.html # 首页-来源选择
│ ├── list.html # 列表-故事列表
│ └── player.html # 播放器-播放+内容
└── static/ # 静态资源
├── css/style.css # 样式(米白/深黑主题)
└── js/app.js # 交互逻辑
```
---
## 📚 数据来源
服务自动扫描 `/home/ubuntu/media/` 目录:
```
/home/ubuntu/media/
├── libraryofshortstories/ # 英语短篇故事
│ ├── the-1000000-bank-note/
│ │ ├── content.txt
│ │ └── metadata.md
│ └── ...
└── public-domain-poetry/ # 公共领域诗歌(可扩展)
└── ...
```
**注意**:添加新来源只需在 `/home/ubuntu/media/` 下创建目录即可。
---
## 🎮 功能说明
### 三页面架构
| 页面 | 路径 | 功能 |
|------|------|------|
| 首页 | `/` | 显示所有内容来源(大卡片) |
| 列表 | `/list/<source>` | 该来源下的故事列表 |
| 播放 | `/play/<source>/<story>` | 播放器 + 文章阅读 |
### 播放器特性
- **固定播放器**:顶部 100px,磨砂玻璃效果
- **流式 TTS**:实时朗读,无需等待完整转换
- **懒加载内容**:长文章分段加载,流畅滑动
- **主题切换**:米白/深黑双主题(点击 🌙/☀️ 切换)
- **阅读进度**:自动保存到 localStorage
- **手势支持**:滑动返回(移动端)
- **独立导航**:返回/关闭按钮,适合 App 内嵌
---
## 🔧 配置说明
### 修改端口
如需修改端口,编辑 `app.py`:
```python
# 默认 8899
app.run(host="0.0.0.0", port=8899, debug=False, threaded=True)
```
然后重启服务:
```bash
sudo systemctl restart audiobook-player
```
### 修改数据目录
如需修改扫描目录,编辑 `app.py`:
```python
MEDIA_DIR = Path("/your/custom/path")
```
---
## 🐛 故障排查
### 服务无法启动
```bash
# 检查端口占用
sudo lsof -i :8899
# 检查日志
sudo journalctl -u audiobook-player -n 50
# 手动测试运行
cd ~/nanocode/audiobook-player
python3 app.py
```
### 页面显示空白
```bash
# 检查媒体目录是否存在
ls -la /home/ubuntu/media/
# 检查目录权限
ls -la ~/nanocode/audiobook-player/static/
```
### TTS 无法播放
```bash
# 检查 edge-tts 是否正常
python3 -c "import edge_tts; print('OK')"
# 测试单个请求
curl "http://129.211.173.87:8899/api/stream?text=hello"
```
---
## 📱 App 内嵌示例
### iOS (WKWebView)
```swift
import WebKit
let webView = WKWebView()
let url = URL(string: "http://129.211.173.87:8899")!
webView.load(URLRequest(url: url))
```
### Android (WebView)
```kotlin
val webView: WebView = findViewById(R.id.webview)
webView.loadUrl("http://129.211.173.87:8899")
```
**特点**:
- 每页独立返回按钮
- 无浏览器地址栏干扰
- 响应式布局适配
---
## 🔒 安全提示
- 服务监听 `0.0.0.0`,所有网卡可访问
- 如需限制访问,可配置防火墙:
```bash
# 只允许本地访问(如需修改)
sudo ufw allow from 127.0.0.1 to any port 8899
```
---
## 📝 更新记录
| 日期 | 版本 | 说明 |
|------|------|------|
| 2026-03-27 | v1.0 | 初始版本,支持流式 TTS、主题切换、懒加载 |
---
## 💡 后续计划
- [ ] 播放速度调节
- [ ] 阅读进度云端同步
- [ ] 收藏功能
- [ ] 多语言语音切换
---
**维护者**: nanobot
**创建时间**: 2026-03-27
+356
View File
@@ -0,0 +1,356 @@
#!/usr/bin/env python3
"""
Audiobook Player - Web Application
Minimalist immersive reading + streaming TTS
Adaptive directory structure support
"""
import os
import json
import asyncio
import edge_tts
from flask import Flask, render_template, request, Response, send_file
from pathlib import Path
from typing import List, Dict, Optional
app = Flask(__name__, static_folder='static')
# Configuration
MEDIA_DIR = Path("/home/ubuntu/media")
DEFAULT_VOICE = "en-US-AriaNeural"
def load_source_config(source_path: Path) -> Optional[Dict]:
"""加载 source.json 配置(如果存在)"""
config_file = source_path / "source.json"
if config_file.exists():
try:
with open(config_file, 'r', encoding='utf-8') as f:
return json.load(f)
except:
pass
return None
def detect_structure_type(source_path: Path) -> str:
"""
自动检测目录结构类型
- flat: 直接存放 txt 文件
- content_folder: 子目录包含 content.txt
- multi_file_folder: 子目录包含多个 txt 文件
"""
# 检查是否有子目录
subdirs = [d for d in source_path.iterdir() if d.is_dir()]
if not subdirs:
# 没有子目录,检查是否有 txt 文件
txt_files = list(source_path.glob("*.txt"))
if txt_files:
return "flat"
return "unknown"
# 有子目录,检查第一个子目录的结构
sample_dir = subdirs[0]
files = list(sample_dir.iterdir())
txt_files = [f for f in files if f.suffix == '.txt']
if len(txt_files) == 1 and txt_files[0].name == 'content.txt':
return "content_folder"
elif len(txt_files) >= 1:
return "multi_file_folder"
return "unknown"
def parse_txt_file(txt_file: Path) -> Dict:
"""解析 txt 文件,提取元数据"""
info = {
"title": txt_file.stem.replace("-", " ").title(),
"author": "Unknown",
"year": None,
"path": str(txt_file),
"has_content": True
}
try:
with open(txt_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines[:10]:
if line.startswith("# "):
info["title"] = line[2:].strip()
elif line.startswith("Author:"):
info["author"] = line[7:].strip()
elif line.startswith("Year:"):
info["year"] = line[5:].strip()
except:
pass
return info
def get_stories_from_flat(source_path: Path) -> List[Dict]:
"""处理扁平结构: /source/poem.txt"""
stories = []
for txt_file in source_path.glob("*.txt"):
info = parse_txt_file(txt_file)
info["id"] = txt_file.stem
info["type"] = "flat"
stories.append(info)
return stories
def get_stories_from_content_folder(source_path: Path) -> List[Dict]:
"""处理 content_folder 结构: /source/story-dir/content.txt"""
stories = []
for story_dir in source_path.iterdir():
if story_dir.is_dir() and story_dir.name != '__pycache__':
content_file = story_dir / "content.txt"
if content_file.exists():
info = parse_txt_file(content_file)
info["id"] = story_dir.name
info["type"] = "content_folder"
stories.append(info)
return stories
def get_stories_from_multi_file_folder(source_path: Path) -> List[Dict]:
"""处理 multi_file_folder 结构: /source/poet-dir/poem.txt"""
stories = []
for poet_dir in source_path.iterdir():
if poet_dir.is_dir() and poet_dir.name != '__pycache__':
poet_name = poet_dir.name.replace("-", " ").title()
for txt_file in poet_dir.glob("*.txt"):
info = parse_txt_file(txt_file)
info["id"] = f"{poet_dir.name}/{txt_file.stem}"
info["title"] = info["title"]
info["author"] = poet_name if info["author"] == "Unknown" else info["author"]
info["type"] = "multi_file_folder"
stories.append(info)
return stories
def get_media_sources():
"""获取所有媒体来源(自适应结构)"""
sources = []
if MEDIA_DIR.exists():
for item in MEDIA_DIR.iterdir():
if item.is_dir():
# 加载配置或自动检测
config = load_source_config(item)
if config:
structure = config.get("structure", "auto")
display_name = config.get("name", format_source_name(item.name))
else:
structure = detect_structure_type(item)
display_name = format_source_name(item.name)
# 统计故事数量
stories = get_stories_from_source(item.name)
sources.append({
"id": item.name,
"name": display_name,
"path": str(item),
"structure": structure,
"count": len(stories)
})
return sorted(sources, key=lambda x: x["name"])
def format_source_name(name):
"""转换目录名称为显示名称"""
name_map = {
"libraryofshortstories": "Library of Short Stories",
"public-domain-poetry": "Public Domain Poetry",
}
return name_map.get(name, name.replace("-", " ").title())
def get_stories_from_source(source_id: str) -> List[Dict]:
"""从来源获取所有故事(自适应结构)"""
source_path = MEDIA_DIR / source_id
if not source_path.exists():
return []
# 获取结构类型
config = load_source_config(source_path)
if config and config.get("structure") != "auto":
structure = config["structure"]
else:
structure = detect_structure_type(source_path)
# 根据结构类型处理
handlers = {
"flat": get_stories_from_flat,
"content_folder": get_stories_from_content_folder,
"multi_file_folder": get_stories_from_multi_file_folder,
}
handler = handlers.get(structure, get_stories_from_content_folder)
stories = handler(source_path)
return sorted(stories, key=lambda x: x["title"])
def read_story_content(source_id: str, story_id: str) -> Optional[str]:
"""读取故事内容(自适应路径)"""
source_path = MEDIA_DIR / source_id
if not source_path.exists():
return None
# 尝试不同的路径格式
possible_paths = [
# content_folder: story-id/content.txt
source_path / story_id / "content.txt",
# multi_file_folder: poet-slug/poem-slug
source_path / f"{story_id}.txt",
# flat: story-id.txt
source_path / f"{story_id}.txt",
]
# 如果 story_id 包含 /,直接解析
if "/" in story_id:
parts = story_id.split("/", 1)
possible_paths.insert(0, source_path / parts[0] / f"{parts[1]}.txt")
for path in possible_paths:
if path.exists():
with open(path, 'r', encoding='utf-8') as f:
return f.read()
return None
# Routes
@app.route("/")
def index():
"""Home page - show media sources"""
sources = get_media_sources()
return render_template("index.html", sources=sources)
@app.route("/list/<source_id>")
def story_list(source_id):
"""Story list page for a source"""
source = None
for s in get_media_sources():
if s["id"] == source_id:
source = s
break
if not source:
return "Source not found", 404
stories = get_stories_from_source(source_id)
return render_template("list.html", source=source, stories=stories)
@app.route("/play/<path:story_path>")
def player(story_path):
"""Player page for a story (支持多级路径)"""
# 解析路径: source_id/story_id 或 source_id/poet/poem
parts = story_path.split("/", 1)
if len(parts) < 2:
return "Invalid story path", 400
source_id = parts[0]
story_id = parts[1]
content = read_story_content(source_id, story_id)
if not content:
return "Story not found", 404
# 解析元数据
title = story_id.replace("-", " ").replace("/", " - ").title()
author = "Unknown"
year = ""
lines = content.split('\n')
body_start = 0
for i, line in enumerate(lines[:20]):
if line.startswith("# "):
title = line[2:].strip()
elif line.startswith("Author:"):
author = line[7:].strip()
elif line.startswith("Year:"):
year = line[5:].strip()
elif line.startswith("==="):
body_start = i + 1
break
body = '\n'.join(lines[body_start:]).strip()
return render_template("player.html",
source_id=source_id,
story_id=story_id,
title=title,
author=author,
year=year,
content=body)
# API Routes
@app.route("/api/sources")
def api_sources():
"""API: Get all sources"""
return json.dumps(get_media_sources())
@app.route("/api/stories/<source_id>")
def api_stories(source_id):
"""API: Get stories from a source"""
return json.dumps(get_stories_from_source(source_id))
async def generate_audio_stream(text, voice=DEFAULT_VOICE, rate="0%"):
"""Generate audio stream using edge-tts with speed control"""
communicate = edge_tts.Communicate(text, voice, rate=rate)
async for chunk in communicate.stream():
if chunk["type"] == "audio":
yield chunk["data"]
@app.route("/api/stream")
def stream_audio():
"""Stream audio from text with speed control"""
text = request.args.get("text", "")
voice = request.args.get("voice", DEFAULT_VOICE)
# edge-tts rate format: [+-]\d+% (e.g., +20%, -20%)
# "0%" is invalid, use "-10%" as default for comfortable speed
rate = request.args.get("rate", "-10%")
if rate == "0%":
rate = "-10%"
if not text:
return "No text provided", 400
def generate():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def stream():
async for chunk in generate_audio_stream(text, voice, rate):
yield chunk
gen = stream()
while True:
try:
chunk = loop.run_until_complete(gen.__anext__())
yield chunk
except StopAsyncIteration:
break
loop.close()
return Response(generate(), mimetype="audio/mpeg")
@app.route("/screenshots/<path:filename>")
def serve_screenshot(filename):
"""提供截图文件下载"""
return send_file(f"static/{filename}")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8899, debug=False, threaded=True)
+16
View File
@@ -0,0 +1,16 @@
[Unit]
Description=Audiobook Player Web Service
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/nanocode/audiobook-player
Environment="HOME=/home/ubuntu"
Environment="PATH=/home/ubuntu/.local/bin:/usr/local/bin:/usr/bin:/bin"
ExecStart=/usr/bin/python3 /home/ubuntu/nanocode/audiobook-player/app.py
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
+2
View File
@@ -0,0 +1,2 @@
Flask>=2.3.0
edge-tts>=6.1.0
+182
View File
@@ -0,0 +1,182 @@
#!/bin/bash
# Audiobook Player - Start Script
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PID_FILE="$SCRIPT_DIR/app.pid"
PORT=5000
show_help() {
echo "📚 Audiobook Player"
echo ""
echo "Usage:"
echo " ./start.sh start # Start server (foreground)"
echo " ./start.sh start-bg # Start server (background)"
echo " ./start.sh stop # Stop server"
echo " ./start.sh status # Check status"
echo " ./start.sh restart # Restart server"
echo ""
echo "URLs:"
echo " Local: http://localhost:$PORT"
echo " Public: http://$(curl -s ifconfig.me 2>/dev/null || echo 'YOUR_IP'):$PORT"
}
check_requirements() {
python3 -c "import flask, edge_tts" 2>/dev/null
if [ $? -ne 0 ]; then
echo "Installing requirements..."
pip3 install -r "$SCRIPT_DIR/requirements.txt"
fi
}
start_server() {
check_requirements
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p "$PID" > /dev/null 2>&1; then
echo "⚠️ Server already running (PID: $PID)"
echo " Visit: http://localhost:$PORT"
return
fi
fi
echo "🚀 Starting Audiobook Player..."
echo " Port: $PORT"
echo ""
cd "$SCRIPT_DIR"
python3 app.py &
# Save PID
echo $! > "$PID_FILE"
sleep 2
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p "$PID" > /dev/null 2>&1; then
echo "✅ Server started (PID: $PID)"
echo ""
echo "📱 Access URLs:"
echo " Local: http://localhost:$PORT"
PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null)
if [ -n "$PUBLIC_IP" ]; then
echo " Public: http://$PUBLIC_IP:$PORT"
fi
fi
fi
}
start_bg() {
check_requirements
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p "$PID" > /dev/null 2>&1; then
echo "⚠️ Server already running (PID: $PID)"
return
fi
fi
echo "🚀 Starting Audiobook Player in background..."
cd "$SCRIPT_DIR"
nohup python3 app.py > "$SCRIPT_DIR/server.log" 2>&1 &
echo $! > "$PID_FILE"
sleep 2
PID=$(cat "$PID_FILE")
if ps -p "$PID" > /dev/null 2>&1; then
echo "✅ Server started (PID: $PID)"
echo ""
echo "📱 Access URLs:"
PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null)
if [ -n "$PUBLIC_IP" ]; then
echo " http://$PUBLIC_IP:$PORT"
fi
echo " http://localhost:$PORT"
echo ""
echo "Logs: tail -f $SCRIPT_DIR/server.log"
fi
}
stop_server() {
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p "$PID" > /dev/null 2>&1; then
echo "⏹️ Stopping server (PID: $PID)..."
kill "$PID"
rm -f "$PID_FILE"
echo "✅ Server stopped"
else
echo "⚠️ Server not running"
rm -f "$PID_FILE"
fi
else
# Try to find and kill by port
PID=$(lsof -ti:$PORT 2>/dev/null)
if [ -n "$PID" ]; then
echo "⏹️ Stopping server (PID: $PID)..."
kill "$PID" 2>/dev/null
echo "✅ Server stopped"
else
echo "⚠️ Server not running"
fi
fi
}
show_status() {
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p "$PID" > /dev/null 2>&1; then
echo "✅ Server is running (PID: $PID)"
echo " Port: $PORT"
echo ""
echo "📱 Access URLs:"
echo " http://localhost:$PORT"
PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null)
if [ -n "$PUBLIC_IP" ]; then
echo " http://$PUBLIC_IP:$PORT"
fi
else
echo "⏹️ Server not running (stale PID file)"
rm -f "$PID_FILE"
fi
else
PID=$(lsof -ti:$PORT 2>/dev/null)
if [ -n "$PID" ]; then
echo "✅ Server is running (PID: $PID)"
else
echo "⏹️ Server not running"
fi
fi
}
case "${1:-help}" in
start)
start_server
;;
start-bg|bg)
start_bg
;;
stop)
stop_server
;;
status)
show_status
;;
restart)
stop_server
sleep 2
start_bg
;;
help|--help|-h)
show_help
;;
*)
echo "❌ Unknown command: $1"
show_help
exit 1
;;
esac
Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

+716
View File
@@ -0,0 +1,716 @@
/* ===== Audiobook Player - Minimalist Immersive Design ===== */
/* CSS Variables for theming */
:root {
--bg-primary: #F5F1E8;
--bg-secondary: #FFFFFF;
--bg-card: #FFFFFF;
--text-primary: #2C2C2C;
--text-secondary: #666666;
--text-muted: #999999;
--accent: #8B7355;
--accent-light: #A68B6A;
--border: #E5E0D5;
--shadow: rgba(0, 0, 0, 0.08);
--player-bg: rgba(255, 255, 255, 0.95);
--progress-bg: #E5E0D5;
--progress-fill: #8B7355;
}
.dark-mode {
--bg-primary: #1A1A1A;
--bg-secondary: #252525;
--bg-card: #2A2A2A;
--text-primary: #E8E1D1;
--text-secondary: #B8B0A0;
--text-muted: #888888;
--accent: #A68B6A;
--accent-light: #C4A882;
--border: #3A3A3A;
--shadow: rgba(0, 0, 0, 0.3);
--player-bg: rgba(40, 40, 40, 0.98);
--progress-bg: #3A3A3A;
--progress-fill: #A68B6A;
}
/* Reset and Base */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-size: 16px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font-family: Georgia, "Times New Roman", serif;
background-color: var(--bg-primary);
color: var(--text-primary);
line-height: 1.6;
transition: background-color 0.3s ease, color 0.3s ease;
overflow-x: hidden;
}
/* App Container */
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
}
/* ===== Header ===== */
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 56px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 16px;
z-index: 1000;
box-shadow: 0 1px 3px var(--shadow);
}
.header-title {
font-size: 1.1rem;
font-weight: 600;
color: var(--text-primary);
flex: 1;
text-align: center;
margin: 0 10px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Navigation Buttons */
.nav-btn {
display: flex;
align-items: center;
gap: 6px;
background: none;
border: none;
color: var(--accent);
font-size: 0.9rem;
cursor: pointer;
padding: 8px 12px;
border-radius: 8px;
transition: background 0.2s;
}
.nav-btn:hover {
background: var(--bg-primary);
}
.nav-icon {
font-size: 0.8rem;
}
.back-btn .nav-text {
display: none;
}
@media (min-width: 400px) {
.back-btn .nav-text {
display: inline;
}
}
/* Theme Toggle */
.theme-toggle {
background: none;
border: none;
font-size: 1.2rem;
cursor: pointer;
padding: 8px;
border-radius: 50%;
transition: transform 0.2s;
}
.theme-toggle:hover {
transform: scale(1.1);
}
/* ===== Main Content ===== */
.main-content {
flex: 1;
padding: 72px 16px 24px;
max-width: 800px;
margin: 0 auto;
width: 100%;
}
/* Welcome Section */
.welcome {
text-align: center;
margin-bottom: 32px;
}
.welcome h2 {
font-size: 1.5rem;
margin-bottom: 8px;
color: var(--text-primary);
}
.subtitle {
color: var(--text-muted);
font-size: 0.9rem;
}
/* ===== Source Cards (Home) ===== */
.sources-grid {
display: grid;
gap: 16px;
}
.source-card {
display: flex;
align-items: center;
gap: 16px;
background: var(--bg-card);
border-radius: 16px;
padding: 20px;
text-decoration: none;
color: inherit;
box-shadow: 0 2px 8px var(--shadow);
transition: transform 0.2s, box-shadow 0.2s;
min-height: 80px;
}
.source-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 16px var(--shadow);
}
.source-icon {
font-size: 2.5rem;
flex-shrink: 0;
}
.source-info {
flex: 1;
}
.source-name {
font-size: 1.1rem;
font-weight: 600;
margin-bottom: 4px;
color: var(--text-primary);
}
.source-count {
font-size: 0.85rem;
color: var(--text-secondary);
}
.source-arrow {
font-size: 1.5rem;
color: var(--text-muted);
}
/* ===== List Page ===== */
.list-header {
margin-bottom: 20px;
}
.list-header h2 {
font-size: 1.1rem;
color: var(--text-secondary);
margin-bottom: 12px;
}
.search-box input {
width: 100%;
padding: 12px 16px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--bg-card);
color: var(--text-primary);
font-size: 1rem;
font-family: inherit;
}
.search-box input:focus {
outline: none;
border-color: var(--accent);
}
.search-box input::placeholder {
color: var(--text-muted);
}
/* Stories List */
.stories-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.story-item {
display: flex;
align-items: center;
gap: 12px;
background: var(--bg-card);
border-radius: 12px;
padding: 16px;
text-decoration: none;
color: inherit;
transition: background 0.2s;
}
.story-item:hover {
background: var(--bg-secondary);
}
.story-number {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-primary);
border-radius: 50%;
font-size: 0.85rem;
color: var(--text-secondary);
flex-shrink: 0;
}
.story-info {
flex: 1;
min-width: 0;
}
.story-title {
font-size: 1rem;
font-weight: 600;
margin-bottom: 4px;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.story-meta {
font-size: 0.8rem;
color: var(--text-secondary);
}
.story-meta .author {
color: var(--accent);
}
.story-arrow {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-primary);
border-radius: 50%;
font-size: 0.7rem;
color: var(--accent);
flex-shrink: 0;
}
/* ===== Player Page ===== */
.player-page {
overflow: hidden;
}
/* Fixed Player Bar (80px) */
.player-bar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 80px;
background: var(--player-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-bottom: 1px solid var(--border);
z-index: 1000;
display: flex;
flex-direction: column;
justify-content: center;
padding: 0 16px;
}
.player-controls {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
}
.player-info {
flex: 1;
min-width: 0;
}
.player-title {
font-size: 0.95rem;
font-weight: 600;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 2px;
}
.player-author {
font-size: 0.8rem;
color: var(--text-secondary);
}
.play-btn, .close-btn {
width: 44px;
height: 44px;
border-radius: 50%;
border: none;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: transform 0.2s;
}
.play-btn {
background: var(--accent);
color: white;
font-size: 1.2rem;
}
.play-btn:hover {
transform: scale(1.05);
background: var(--accent-light);
}
.close-btn {
background: var(--bg-primary);
color: var(--text-secondary);
font-size: 1rem;
}
.close-btn:hover {
color: var(--text-primary);
}
/* Progress Bar */
.progress-container {
display: flex;
align-items: center;
gap: 10px;
padding-top: 8px;
}
.time-current, .time-total {
font-size: 0.7rem;
color: var(--text-muted);
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
min-width: 35px;
}
.time-total {
text-align: right;
}
/* Speed Control Bar */
.speed-control-bar {
position: fixed;
top: 80px;
left: 0;
right: 0;
height: 44px;
background: var(--player-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-bottom: 1px solid var(--border);
z-index: 999;
display: flex;
align-items: center;
justify-content: center;
gap: 40px;
padding: 0 20px;
}
.speed-btn {
background: none;
border: none;
color: var(--text-secondary);
font-size: 0.9rem;
font-family: inherit;
cursor: pointer;
padding: 6px 16px;
border-radius: 16px;
transition: all 0.2s;
min-width: 60px;
}
.speed-btn:hover {
color: var(--text-primary);
background: var(--bg-primary);
}
.speed-btn.active {
color: white;
background: var(--accent);
}
/* Content Area with Speed Control */
.content-area.player-with-speed {
margin-top: 124px; /* 80px player + 44px speed control */
}
.progress-bar {
flex: 1;
height: 4px;
background: var(--progress-bg);
border-radius: 2px;
cursor: pointer;
position: relative;
}
.progress-fill {
height: 100%;
background: var(--progress-fill);
border-radius: 2px;
width: 0%;
transition: width 0.1s linear;
}
/* Content Area */
.content-area {
margin-top: 80px;
padding: 20px 16px 40px;
height: calc(100vh - 80px);
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
.content-area.player-with-speed {
margin-top: 124px; /* 80px player + 44px speed control */
height: calc(100vh - 124px);
}
.story-content {
max-width: 680px;
margin: 0 auto;
}
.content-header {
margin-bottom: 32px;
padding-bottom: 24px;
border-bottom: 1px solid var(--border);
}
.content-header h1 {
font-size: 1.6rem;
line-height: 1.3;
margin-bottom: 12px;
color: var(--text-primary);
}
.content-meta {
font-size: 0.9rem;
color: var(--text-secondary);
}
.content-meta .author {
color: var(--accent);
font-weight: 500;
}
.content-meta .year {
margin-left: 8px;
padding-left: 8px;
border-left: 1px solid var(--border);
}
/* Content Body */
.content-body {
font-size: 1.1rem;
line-height: 1.8;
color: var(--text-primary);
}
.content-chunk {
margin-bottom: 24px;
transition: opacity 0.3s ease;
}
.content-chunk p {
margin-bottom: 1.2em;
text-align: justify;
hyphens: auto;
}
.content-chunk p:last-child {
margin-bottom: 0;
}
/* Loading State */
.loading {
text-align: center;
padding: 40px;
color: var(--text-muted);
}
/* Content End */
.content-end {
text-align: center;
padding: 48px 0;
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 48px;
}
.content-end p {
font-style: italic;
margin-bottom: 24px;
}
.back-to-list {
padding: 12px 32px;
background: var(--accent);
color: white;
border: none;
border-radius: 24px;
font-size: 0.95rem;
cursor: pointer;
transition: background 0.2s;
}
.back-to-list:hover {
background: var(--accent-light);
}
/* ===== Empty State ===== */
.empty-state {
text-align: center;
padding: 60px 20px;
color: var(--text-muted);
}
.empty-state p {
font-size: 1.1rem;
margin-bottom: 8px;
}
.empty-subtitle {
font-size: 0.85rem !important;
}
/* ===== Footer ===== */
.footer {
text-align: center;
padding: 20px;
color: var(--text-muted);
font-size: 0.8rem;
border-top: 1px solid var(--border);
}
/* ===== Responsive Adjustments ===== */
@media (min-width: 768px) {
.main-content {
padding-top: 80px;
}
.content-area {
padding: 32px 40px;
}
.content-body {
font-size: 1.2rem;
line-height: 1.9;
}
}
@media (min-width: 1024px) {
.player-bar {
left: auto;
width: 380px;
right: 0;
top: 0;
bottom: 0;
height: auto;
border-left: 1px solid var(--border);
border-bottom: none;
flex-direction: column-reverse;
justify-content: flex-end;
padding: 24px;
}
.player-controls {
flex-direction: column;
gap: 20px;
}
.player-info {
text-align: center;
}
.progress-container {
padding-top: 0;
padding-bottom: 20px;
}
.content-area {
margin-top: 0;
margin-right: 380px;
height: 100vh;
}
.content-area.player-with-speed {
margin-top: 0;
margin-right: 380px;
height: 100vh;
}
.speed-control-bar {
left: auto;
right: 0;
top: auto;
bottom: 0;
width: 380px;
height: 60px;
border-top: 1px solid var(--border);
border-bottom: none;
border-left: 1px solid var(--border);
}
}
/* ===== Scrollbar Styling ===== */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
/* ===== Selection ===== */
::selection {
background: var(--accent-light);
color: white;
}
.dark-mode ::selection {
background: var(--accent);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 638 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 779 KiB

+252
View File
@@ -0,0 +1,252 @@
/**
* Audiobook Player - App JavaScript
* Minimalist immersive reading experience
*/
// Theme Management
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
if (savedTheme === 'dark') {
document.body.classList.remove('light-mode');
document.body.classList.add('dark-mode');
updateThemeIcon(true);
}
}
function toggleTheme() {
const isDark = document.body.classList.contains('dark-mode');
if (isDark) {
document.body.classList.remove('dark-mode');
document.body.classList.add('light-mode');
localStorage.setItem('theme', 'light');
} else {
document.body.classList.remove('light-mode');
document.body.classList.add('dark-mode');
localStorage.setItem('theme', 'dark');
}
updateThemeIcon(!isDark);
}
function updateThemeIcon(isDark) {
const toggle = document.querySelector('.theme-toggle');
if (toggle) {
toggle.textContent = isDark ? '☀️' : '🌙';
}
}
// Navigation
function goBack() {
window.history.back();
}
function closePlayer() {
// Override in player page
window.history.back();
}
// Save and Restore Reading Position
function saveReadingPosition(storyId, scrollPosition) {
const positions = JSON.parse(localStorage.getItem('readingPositions') || '{}');
positions[storyId] = {
position: scrollPosition,
timestamp: Date.now()
};
localStorage.setItem('readingPositions', JSON.stringify(positions));
}
function getReadingPosition(storyId) {
const positions = JSON.parse(localStorage.getItem('readingPositions') || '{}');
return positions[storyId]?.position || 0;
}
// Smooth Scroll
function scrollToPosition(position) {
window.scrollTo({
top: position,
behavior: 'smooth'
});
}
// Touch Gestures (for mobile)
let touchStartX = 0;
let touchEndX = 0;
function initTouchGestures() {
document.addEventListener('touchstart', (e) => {
touchStartX = e.changedTouches[0].screenX;
}, { passive: true });
document.addEventListener('touchend', (e) => {
touchEndX = e.changedTouches[0].screenX;
handleSwipe();
}, { passive: true });
}
function handleSwipe() {
const swipeThreshold = 100;
const diff = touchStartX - touchEndX;
// Swipe right (go back)
if (diff < -swipeThreshold) {
// Only if we're not on the home page
if (window.location.pathname !== '/') {
goBack();
}
}
}
// Keyboard Shortcuts
function initKeyboardShortcuts() {
document.addEventListener('keydown', (e) => {
// Space: Play/Pause (on player page)
if (e.code === 'Space' && document.getElementById('playBtn')) {
e.preventDefault();
togglePlay();
}
// Escape: Go back
if (e.code === 'Escape') {
if (window.location.pathname !== '/') {
goBack();
}
}
});
}
// Audio Player Enhancements
function initAudioPlayer() {
const audio = document.getElementById('audioPlayer');
if (!audio) return;
// Handle errors
audio.addEventListener('error', (e) => {
console.error('Audio error:', e);
showNotification('播放出错,请重试');
});
// Handle ended
audio.addEventListener('ended', () => {
isPlaying = false;
updatePlayButton();
});
// Handle loading
audio.addEventListener('loadstart', () => {
showNotification('加载中...', 1000);
});
}
// Notification System
function showNotification(message, duration = 3000) {
// Remove existing notification
const existing = document.querySelector('.notification');
if (existing) {
existing.remove();
}
const notification = document.createElement('div');
notification.className = 'notification';
notification.textContent = message;
notification.style.cssText = `
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: var(--bg-card);
color: var(--text-primary);
padding: 12px 24px;
border-radius: 24px;
box-shadow: 0 4px 16px var(--shadow);
z-index: 9999;
font-size: 0.9rem;
animation: slideUp 0.3s ease;
`;
document.body.appendChild(notification);
if (duration > 0) {
setTimeout(() => {
notification.style.animation = 'slideDown 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, duration);
}
return notification;
}
// Add animation styles
const style = document.createElement('style');
style.textContent = `
@keyframes slideUp {
from {
opacity: 0;
transform: translateX(-50%) translateY(20px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@keyframes slideDown {
from {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
to {
opacity: 0;
transform: translateX(-50%) translateY(20px);
}
}
`;
document.head.appendChild(style);
// Prefetch next chunk (optimization)
function prefetchNextChunk(currentIndex) {
// Implementation for preloading next audio chunk
// This would be implemented in player.html
}
// Performance: Debounce scroll events
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', () => {
initTheme();
initTouchGestures();
initKeyboardShortcuts();
initAudioPlayer();
});
// Handle page visibility change (pause when switching tabs)
document.addEventListener('visibilitychange', () => {
const audio = document.getElementById('audioPlayer');
if (document.hidden && audio && !audio.paused) {
// Optional: pause when switching tabs
// audio.pause();
// isPlaying = false;
// updatePlayButton();
}
});
// Prevent zoom on double tap (mobile)
let lastTouchEnd = 0;
document.addEventListener('touchend', (event) => {
const now = Date.now();
if (now - lastTouchEnd <= 300) {
event.preventDefault();
}
lastTouchEnd = now;
}, { passive: false });
Binary file not shown.

After

Width:  |  Height:  |  Size: 778 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 593 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 590 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 586 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 634 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 583 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

+61
View File
@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Audiobook Player</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body class="light-mode">
<div class="app">
<!-- Header -->
<header class="header">
<h1 class="header-title">📚 Audiobook</h1>
<button class="theme-toggle" onclick="toggleTheme()">🌙</button>
</header>
<!-- Main Content -->
<main class="main-content">
<div class="welcome">
<h2>选择阅读来源</h2>
<p class="subtitle">Select your reading source</p>
</div>
<div class="sources-grid">
{% for source in sources %}
<a href="/list/{{ source.id }}" class="source-card">
<div class="source-icon">
{% if 'library' in source.id.lower() %}
📚
{% elif 'poetry' in source.id.lower() %}
📝
{% elif 'loyal' in source.id.lower() %}
🎧
{% else %}
📖
{% endif %}
</div>
<div class="source-info">
<h3 class="source-name">{{ source.name }}</h3>
<p class="source-count">{{ source.count }} 个项目</p>
</div>
<div class="source-arrow">→</div>
</a>
{% else %}
<div class="empty-state">
<p>暂无内容</p>
<p class="empty-subtitle">No media sources found</p>
</div>
{% endfor %}
</div>
</main>
<!-- Footer -->
<footer class="footer">
<p>© 2026 Audiobook Player</p>
</footer>
</div>
<script src="/static/js/app.js"></script>
</body>
</html>
+72
View File
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>{{ source.name }} - Audiobook</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body class="light-mode">
<div class="app">
<!-- Header with back button -->
<header class="header">
<button class="nav-btn back-btn" onclick="goBack()">
<span class="nav-icon">◀</span>
<span class="nav-text">返回</span>
</button>
<h1 class="header-title">{{ source.name }}</h1>
<button class="theme-toggle" onclick="toggleTheme()">🌙</button>
</header>
<!-- Search Bar -->
<div class="search-bar">
<input type="text" id="searchInput" class="search-input" placeholder="搜索故事标题或作者..." onkeyup="searchStories()">
<span class="search-icon">🔍</span>
</div>
<!-- Stories List -->
<main class="main-content">
<div class="stories-list" id="storiesList">
{% for story in stories %}
<a href="/play/{{ source.id }}/{{ story.id }}" class="story-item" data-title="{{ story.title | lower }}" data-author="{{ story.author | lower }}">
<div class="story-number">{{ loop.index }}</div>
<div class="story-info">
<h3 class="story-title">{{ story.title }}</h3>
<p class="story-meta">
<span class="author">{{ story.author }}</span>
{% if story.year %}
<span class="year">· {{ story.year }}</span>
{% endif %}
</p>
</div>
<div class="story-arrow">▶</div>
</a>
{% else %}
<div class="empty-state">
<p>暂无故事</p>
<p class="empty-subtitle">No stories found in this source</p>
</div>
{% endfor %}
</div>
</main>
</div>
<script src="/static/js/app.js"></script>
<script>
function searchStories() {
const query = document.getElementById('searchInput').value.toLowerCase();
const items = document.querySelectorAll('.story-item');
items.forEach(item => {
const title = item.dataset.title;
const author = item.dataset.author;
if (title.includes(query) || author.includes(query)) {
item.style.display = 'flex';
} else {
item.style.display = 'none';
}
});
}
</script>
</body>
</html>
+147
View File
@@ -0,0 +1,147 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>{{ title }} - Audiobook</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body class="light-mode player-page">
<div class="app">
<!-- Fixed Player Bar (80px height) -->
<div class="player-bar" id="playerBar">
<div class="player-controls">
<button class="nav-btn back-btn" onclick="goBack()">
<span class="nav-icon">◀</span>
</button>
<div class="player-info">
<h3 class="player-title">{{ title }}</h3>
<p class="player-author">{{ author }}</p>
</div>
<button class="play-btn" id="playBtn" onclick="togglePlay()">
<span class="play-icon">▶</span>
</button>
<button class="close-btn" onclick="closePlayer()">
<span class="close-icon">✕</span>
</button>
</div>
<!-- Audio Element -->
<audio id="audioPlayer" preload="none"></audio>
</div>
<!-- Speed Control Bar -->
<div class="speed-control-bar" id="speedControlBar">
<button class="speed-btn" data-rate="-30%" onclick="setSpeed(this, '-30%')">慢</button>
<button class="speed-btn active" data-rate="-10%" onclick="setSpeed(this, '-10%')">正常</button>
<button class="speed-btn" data-rate="+10%" onclick="setSpeed(this, '+10%')">快</button>
</div>
<!-- Content Area (scrollable) -->
<main class="content-area player-with-speed" id="contentArea">
<article class="story-content" id="storyContent">
<header class="content-header">
<h1>{{ title }}</h1>
<p class="content-meta">
<span class="author">{{ author }}</span>
{% if year %}
<span class="year">{{ year }}</span>
{% endif %}
</p>
</header>
<div class="content-body" id="contentBody">
{{ content | safe }}
</div>
<div class="content-end">
<p>— End of Story —</p>
<button class="back-to-list" onclick="goBack()">返回列表</button>
</div>
</article>
</main>
</div>
<script src="/static/js/app.js"></script>
<script>
// Story content
const storyContent = {{ content | tojson }};
const storyTitle = {{ title | tojson }};
// Audio state
let isPlaying = false;
let audioPlayer = document.getElementById('audioPlayer');
let playBtn = document.getElementById('playBtn');
let currentSpeed = '-10%';
// Toggle play/pause
function togglePlay() {
if (isPlaying) {
pauseAudio();
} else {
playAudio();
}
}
function playAudio() {
const text = storyContent || storyTitle;
if (!text) return;
const streamUrl = `/api/stream?text=${encodeURIComponent(text)}&rate=${encodeURIComponent(currentSpeed)}`;
audioPlayer.src = streamUrl;
audioPlayer.play();
isPlaying = true;
updatePlayButton();
}
function pauseAudio() {
audioPlayer.pause();
isPlaying = false;
updatePlayButton();
}
function updatePlayButton() {
playBtn.innerHTML = isPlaying ? '<span class="pause-icon">⏸</span>' : '<span class="play-icon">▶</span>';
}
// Speed control
function setSpeed(btn, rate) {
document.querySelectorAll('.speed-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentSpeed = rate;
if (isPlaying) {
pauseAudio();
playAudio();
}
}
// Handle audio ended
audioPlayer.addEventListener('ended', () => {
isPlaying = false;
updatePlayButton();
});
// Handle audio error
audioPlayer.addEventListener('error', (e) => {
console.error('Audio error:', e);
isPlaying = false;
updatePlayButton();
});
function closePlayer() {
pauseAudio();
window.location.href = '/list/{{ source_id }}';
}
function goBack() {
pauseAudio();
window.history.back();
}
</script>
</body>
</html>