from flask import Flask, request, send_file, jsonify from flask_cors import CORS import dashscope from dashscope.audio.tts_v2 import SpeechSynthesizer import hashlib import os app = Flask(__name__) CORS(app) # 允许所有域名跨域访问 # 配置 CACHE_FOLDER = 'audio_cache' MODEL = "cosyvoice-v1" VOICE = "longxiaochun" # 确保缓存文件夹存在 os.makedirs(CACHE_FOLDER, exist_ok=True) def get_md5(text): """生成文本的MD5哈希值""" return hashlib.md5(text.encode('utf-8')).hexdigest() def generate_audio(text, output_path): """使用DashScope生成语音文件""" synthesizer = SpeechSynthesizer(model=MODEL, voice=VOICE) audio = synthesizer.call(text) with open(output_path, 'wb') as f: f.write(audio) return synthesizer.get_last_request_id() @app.route('/tts', methods=['POST', 'OPTIONS']) def text_to_speech(): if request.method == 'OPTIONS': return jsonify({}), 200 # 获取请求数据 data = request.get_json() if not data or 'text' not in data: return jsonify({'error': 'Missing text parameter'}), 400 text = data['text'] # 生成文件名 filename = get_md5(text) + '.mp3' filepath = os.path.join(CACHE_FOLDER, filename) # 检查缓存 if not os.path.exists(filepath): try: request_id = generate_audio(text, filepath) print(f'Generated new audio file with requestId: {request_id}') except Exception as e: return jsonify({'error': f'Failed to generate audio: {str(e)}'}), 500 # 返回音频文件 try: return send_file( filepath, mimetype='audio/mpeg', as_attachment=True, download_name=f'tts_{filename}' ) except Exception as e: return jsonify({'error': f'Failed to send audio file: {str(e)}'}), 500 if __name__ == '__main__': app.run(host='0.0.0.0', port=15001, debug=True)