|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我用flask写了一个听力的app,只有第一个单词发声音,后面就没有声音了,怎么回事?
app.py
- from flask import Flask, render_template, request, jsonify
- import json
- import random
- import pyttsx3
- import threading
- import time
- import os
- app = Flask(__name__)
- current_dir = os.path.join(os.path.abspath(__file__))
- parent_dir = os.path.dirname(current_dir)
- filepath = os.path.join(parent_dir, 'words.json')
- # Load words from JSON file
- with open(filepath, 'r', encoding='utf-8') as f:
- words_dict = json.load(f)
- # Initialize TTS engine
- engine = pyttsx3.init()
- engine.setProperty("rate", 100)
- engine.setProperty("volume", 1)
- voices = engine.getProperty("voices")
- # Global control variables
- is_paused = False
- stop_thread = False
- @app.route('/')
- def index():
- return render_template('index.html')
- @app.route('/start', methods=['POST'])
- def start():
- global is_paused, stop_thread
- is_paused = False
- stop_thread = False
- language = request.form['language']
- num_words = int(request.form['num_words'])
- sleep_time = float(request.form['sleep_time'])
- order = request.form['order']
- words = list(words_dict.keys()) if language == 'english' else list(words_dict.values())
- selected_words = random.sample(words, num_words) if order == 'random' else words[:num_words]
- t = threading.Thread(target=display_and_pronounce, args=(selected_words, sleep_time, language))
- t.start()
- return jsonify({'status': 'started'})
- @app.route('/pause', methods=['POST'])
- def pause():
- global is_paused
- is_paused = not is_paused
- return jsonify({'status': 'paused' if is_paused else 'resumed'})
- @app.route('/stop', methods=['POST'])
- def stop():
- global stop_thread
- stop_thread = True
- return jsonify({'status': 'stopped'})
- def display_and_pronounce(words, sleep_time, language):
- global is_paused, stop_thread
- engine.setProperty('voice', voices[1].id if language == 'english' else voices[0].id)
- for word in words:
- if stop_thread:
- break
- while is_paused:
- time.sleep(0.1)
- gap = calculate_gap(word, sleep_time)
- engine.say(word)
- engine.runAndWait()
- time.sleep(gap)
- engine.say(word)
- engine.runAndWait()
- time.sleep(gap)
- def calculate_gap(word, sleep_time):
- length = len(word.split(" "))
- if length == 1:
- return 2 * sleep_time
- elif length == 2:
- return 3 * sleep_time
- elif length == 3:
- return 5 * sleep_time
- else:
- return 9 * sleep_time
- if __name__ == "__main__":
- app.run(debug=True)
复制代码
templates/index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Language Learning App</title>
- <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
- </head>
- <body>
- <div class="container">
- <h1>Language Learning App</h1>
- <form id="control-form">
- <label for="language">Select Language:</label>
- <select id="language" name="language">
- <option value="english">English</option>
- <option value="chinese">Chinese</option>
- </select>
- <br>
- <label for="num_words">Number of Words:</label>
- <input type="number" id="num_words" name="num_words" value="10">
- <br>
- <label for="sleep_time">Sleep Time (seconds):</label>
- <input type="number" step="0.1" id="sleep_time" name="sleep_time" value="1.0">
- <br>
- <label for="order">Order:</label>
- <select id="order" name="order">
- <option value="sequential">Sequential</option>
- <option value="random">Random</option>
- </select>
- <br>
- <button type="button" onclick="startLearning()">Start</button>
- <button type="button" onclick="pauseLearning()">Pause/Resume</button>
- <button type="button" onclick="stopLearning()">Stop</button>
- </form>
- </div>
- <script>
- function startLearning() {
- $.post('/start', $('#control-form').serialize(), function(data) {
- console.log(data.status);
- });
- }
- function pauseLearning() {
- $.post('/pause', function(data) {
- console.log(data.status);
- });
- }
- function stopLearning() {
- $.post('/stop', function(data) {
- console.log(data.status);
- });
- }
- </script>
- </body>
- </html>
复制代码
static/style.css
- body {
- font-family: Arial, sans-serif;
- background-color: #f4f4f4;
- text-align: center;
- padding: 50px;
- }
- .container {
- background-color: #fff;
- padding: 20px;
- border-radius: 5px;
- box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
- display: inline-block;
- text-align: left;
- }
- h1 {
- margin-bottom: 20px;
- }
- label {
- display: block;
- margin: 10px 0 5px;
- }
- input, select, button {
- width: 100%;
- padding: 10px;
- margin: 5px 0;
- border-radius: 5px;
- border: 1px solid #ccc;
- }
- button {
- background-color: #28a745;
- color: white;
- border: none;
- cursor: pointer;
- }
- button:hover {
- background-color: #218838;
- }
复制代码 |
|