我用AI做的3/100件事之废旧手机变英语磨耳朵神器 背景:从废旧手机到学习工具你有没有一台旧手机躺在抽屉里吃灰?我有一台2018年的华为P20,屏幕有划痕,电池续航只剩半天,但运行Android系统毫无问题。我一直在想:如何让它重新发挥价值?直到有一天,我看到了“磨耳朵”这个概念——通过反复听英语音频来培养语感。而AI,特别是语音合成(TTS)技术,可以让我把任何文本转成自然流畅的英语语音。于是,我决定用这台废旧手机打造一个“英语磨耳朵神器”:一个可以自动朗读英语文本、支持断点续播、还能通过AI生成定制内容的播放器。整个过程只需要3个小时,总共花费0元(除了电费)。## 核心思路:用Python搭建本地服务器我的方案是:在旧手机上安装一个轻量级Python环境(比如Termux),然后运行一个Flask服务器。这个服务器会:1. 接收用户上传的英语文本(比如新闻、小说、单词表)2. 调用AI语音合成API(我用了gTTS,免费且支持自然语音)3. 生成mp3音频文件并缓存4. 提供Web界面进行播放控制这样,我的旧手机就变成了一个“智能听力播放器”,而且完全不依赖其他设备。## 第一步:在旧手机上安装Python环境首先,在旧手机上下载Termux(一个Android终端模拟器,可从F-Droid或GitHub获取)。然后执行:bashpkg updatepkg install pythonpip install flask gtts注意:如果gTTS下载失败,可以先用pkg install python-pip安装pip。整个过程大约需要5分钟。## 第二步:编写核心代码下面是我的第一个代码示例——一个完整的Flask应用,它接收文本、调用gTTS生成语音、并提供播放接口。python# app.py - 废旧手机变身英语听力服务器from flask import Flask, render_template_string, request, send_file, jsonifyfrom gtts import gTTSimport osimport uuidimport threadingapp = Flask(__name__)AUDIO_DIR = "audio_cache" # 缓存音频文件的目录os.makedirs(AUDIO_DIR, exist_ok=True)# 简单的HTML界面(磨耳朵播放器)HTML_TEMPLATE = """<!DOCTYPE html><html><head> <title>英语磨耳朵神器</title> <meta charset="utf-8"> <style> body { font-family: Arial; max-width: 600px; margin: auto; padding: 20px; background: #f5f5f5; } textarea { width: 100%; height: 200px; margin: 10px 0; } audio { width: 100%; } button { background: #4CAF50; color: white; padding: 10px 20px; border: none; cursor: pointer; } </style></head><body> <h1>📖 英语磨耳朵神器</h1> <form id="textForm"> <label>输入英语文本(支持长文):</label> <textarea id="textInput" placeholder="Paste your English text here..."></textarea> <button type="submit">生成并播放</button> </form> <h3>播放器</h3> <audio id="player" controls> Your browser does not support the audio element. </audio> <p id="status">等待输入...</p> <script> document.getElementById('textForm').onsubmit = async function(e) { e.preventDefault(); const text = document.getElementById('textInput').value; if (!text.trim()) return; document.getElementById('status').textContent = '正在生成语音...'; // 发送文本到服务器 const response = await fetch('/generate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({text: text}) }); const data = await response.json(); if (data.success) { // 自动播放生成的音频 const player = document.getElementById('player'); player.src = data.audio_url; player.play(); document.getElementById('status').textContent = '✅ 语音已生成,正在播放!'; } else { document.getElementById('status').textContent = '❌ 错误: ' + data.error; } }; </script></body></html>"""@app.route('/')def index(): """主页面:返回磨耳朵播放器界面""" return render_template_string(HTML_TEMPLATE)@app.route('/generate', methods=['POST'])def generate_audio(): """ API接口:接收文本,生成语音音频文件 使用gTTS将英语文本转为自然语音,并返回可访问的音频URL """ data = request.get_json() text = data.get('text', '') if not text or len(text) > 5000: # 限制文本长度,避免内存溢出 return jsonify({'success': False, 'error': '文本不能为空或超过5000字符'}) try: # 生成唯一文件名,避免冲突 filename = f"audio_{uuid.uuid4().hex}.mp3" filepath = os.path.join(AUDIO_DIR, filename) # 使用gTTS生成语音(lang='en'表示英语) tts = gTTS(text=text, lang='en', slow=False) # slow=False表示正常语速 tts.save(filepath) # 返回音频文件的URL audio_url = f"/audio/{filename}" return jsonify({'success': True, 'audio_url': audio_url}) except Exception as e: return jsonify({'success': False, 'error': str(e)})@app.route('/audio/<filename>')def serve_audio(filename): """提供音频文件下载""" filepath = os.path.join(AUDIO_DIR, filename) if os.path.exists(filepath): return send_file(filepath, mimetype='audio/mpeg') else: return "File not found", 404if __name__ == '__main__': # 在手机的局域网IP上运行,端口5000 # 0.0.0.0表示监听所有网络接口,这样同一WiFi下的其他设备也能访问 print("磨耳朵神器启动!请在浏览器访问 http://<手机IP>:5000") app.run(host='0.0.0.0', port=5000, debug=False)运行代码:在Termux中执行python app.py,然后在手机浏览器打开http://localhost:5000,就能看到播放器界面了。## 第三步:增强功能——AI智能分段与重复播放基础版只能播放一整段文本,但“磨耳朵”需要反复听重点内容。于是我添加了第二个功能:AI自动将文本按句子分段,并支持每个句子重复播放N次。python# enhanced_player.py - 智能分段与重复播放功能import refrom flask import Flask, render_template_string, request, send_file, jsonifyfrom gtts import gTTSimport osimport uuidapp = Flask(__name__)AUDIO_DIR = "audio_cache"os.makedirs(AUDIO_DIR, exist_ok=True)# 增强版HTML界面:支持分段和重复ENHANCED_HTML = """<!DOCTYPE html><html><head> <title>智能磨耳朵播放器</title> <meta charset="utf-8"> <style> body { font-family: Arial; max-width: 800px; margin: auto; padding: 20px; } .sentence { padding: 5px; margin: 2px; cursor: pointer; border-radius: 3px; } .sentence:hover { background: #e0f7fa; } .active { background: #4CAF50; color: white; } .controls { margin: 20px 0; } .sentence-list { max-height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; } </style></head><body> <h1>🧠 智能磨耳朵神器(AI分段+重复)</h1> <div> <textarea id="textInput" rows="5" cols="80" placeholder="输入英语文本..."></textarea> <br> <label>重复次数: <input type="number" id="repeatCount" value="3" min="1" max="10"></label> <button onclick="processText()">AI分段并生成</button> </div> <div class="controls"> <h3>句子列表(点击可单独播放)</h3> <div id="sentenceList" class="sentence-list"></div> <div> <button onclick="playAll()">▶ 顺序播放所有句子</button> <button onclick="toggleLoop()">🔄 切换循环模式</button> <span id="loopStatus">循环: 关</span> </div> </div> <audio id="player" controls style="width: 100%; margin-top: 20px;"></audio> <p id="status">就绪</p> <script> let sentences = []; let currentIndex = 0; let isLooping = false; // 调用AI分段API async function processText() { const text = document.getElementById('textInput').value; const repeat = document.getElementById('repeatCount').value; if (!text.trim()) return; document.getElementById('status').textContent = '正在AI分段...'; const response = await fetch('/split_sentences', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({text: text, repeat: parseInt(repeat)}) }); const data = await response.json(); if (data.success) { sentences = data.sentences; displaySentences(); document.getElementById('status').textContent = `✅ 分段完成,共${sentences.length}个句子`; } else { document.getElementById('status').textContent = '❌ 错误: ' + data.error; } } function displaySentences() { const container = document.getElementById('sentenceList'); container.innerHTML = ''; sentences.forEach((s, idx) => { const div = document.createElement('div'); div.className = 'sentence'; div.textContent = `${idx+1}. ${s.text}`; div.onclick = () => playSentence(idx); div.id = `sentence-${idx}`; container.appendChild(div); }); } function playSentence(index) { currentIndex = index; const player = document.getElementById('player'); player.src = sentences[index].audio_url; player.play(); highlightSentence(index); } function highlightSentence(index) { document.querySelectorAll('.sentence').forEach(el => el.classList.remove('active')); const el = document.getElementById(`sentence-${index}`); if (el) el.classList.add('active'); } async function playAll() { if (sentences.length === 0) return; currentIndex = 0; // 顺序播放:每次播放完自动播下一个 const player = document.getElementById('player'); player.onended = function() { currentIndex++; if (currentIndex < sentences.length) { playSentence(currentIndex); } else if (isLooping) { currentIndex = 0; playSentence(0); } }; playSentence(0); } function toggleLoop() { isLooping = !isLooping; document.getElementById('loopStatus').textContent = `循环: ${isLooping ? '开' : '关'}`; } </script></body></html>"""def split_into_sentences(text): """AI分段:使用正则表达式将文本按句子分隔符拆分 支持英文句号、问号、感叹号,并保留分隔符""" # 使用正向先行断言,保留分隔符 sentences = re.split(r'(?<=[.!?])\s+', text.strip()) # 过滤掉空字符串 return [s.strip() for s in sentences if s.strip()]@app.route('/enhanced')def enhanced_index(): """增强版主页面""" return render_template_string(ENHANCED_HTML)@app.route('/split_sentences', methods=['POST'])def split_and_generate(): """API:分段并生成所有句子的音频""" data = request.get_json() text = data.get('text', '') repeat = data.get('repeat', 3) if not text: return jsonify({'success': False, 'error': '文本不能为空'}) try: # AI分段 raw_sentences = split_into_sentences(text) if len(raw_sentences) > 100: # 限制分段数量 return jsonify({'success': False, 'error': '句子数量超过100个,请缩短文本'}) result_sentences = [] for s in raw_sentences: # 为每个句子生成音频 filename = f"sentence_{uuid.uuid4().hex}.mp3" filepath = os.path.join(AUDIO_DIR, filename) tts = gTTS(text=s, lang='en', slow=False) tts.save(filepath) audio_url = f"/audio/{filename}" result_sentences.append({ 'text': s, 'audio_url': audio_url, 'repeat': repeat # 保留重复次数供前端使用 }) return jsonify({'success': True, 'sentences': result_sentences}) except Exception as e: return jsonify({'success': False, 'error': str(e)})if __name__ == '__main__': print("智能磨耳朵神器启动!访问 http://<手机IP>:5000/enhanced 使用增强版") app.run(host='0.0.0.0', port=5000, debug=False)这个增强版的核心是split_into_sentences函数,它使用正则表达式将英文文本拆分成独立的句子。同时,前端实现了“顺序播放”和“循环模式”,让你可以反复听整篇文章,直到耳朵“磨出茧子”。## 实际使用场景与优化我每天用这个系统做三件事:1.晨间新闻 :从BBC或CNN复制一篇短文,让手机朗读,边刷牙边听。2.单词表 :把生词和例句写成一个段落,AI自动分段后,每个句子重复3遍,加深记忆。3.睡前故事 :英语童话或小说片段,设置循环播放,听着入睡。性能优化小技巧 :- 旧手机内存有限,我在代码中加入了文本长度限制(5000字符)。- 音频文件会缓存在audio_cache目录,可以用cron定期清理。- 如果gTTS网络请求慢,可以改用Edge TTS(微软免费API),音质更好。## 总结这个项目仅用了两个Python文件、不到150行代码,就让一台闲置的旧手机变成了全功能英语听力学习机。核心思路是:利用AI语音合成+本地轻量服务器,把任何英语文本转为可交互的音频播放器 。从技术角度看,涉及了Flask Web框架、gTTS API调用、正则表达式文本处理、前端音频控制等知识点。但更重要的是,它展示了AI如何赋能日常学习——你不需要昂贵的设备或复杂的系统,只需要一点创意和代码,就能将旧电子设备变成高效的学习工具。现在,我的旧手机每天固定在书桌上,连着充电器,充当我的“英语磨耳朵助手”。如果你也有一台闲置的Android手机,不妨试试这个方案——它可能比任何英语App都更“听话”,因为你可以完全定制它。