flask向网页实时传递音频流的前端后端完整代码
时间: 2023-10-19 19:35:32 浏览: 541
您好,下面是一个使用 Flask 和 PyAudio 实现向网页实时传递音频流的前端和后端完整代码:
前端代码(HTML 和 JavaScript):
```html
<!DOCTYPE html>
<html>
<head>
<title>Real-time Audio Streaming with Flask and PyAudio</title>
</head>
<body>
<h1>Real-time Audio Streaming with Flask and PyAudio</h1>
<div>
<button onclick="startRecording()">Start Recording</button>
<button onclick="stopRecording()">Stop Recording</button>
</div>
<div>
<audio id="audio" controls></audio>
</div>
<script>
var ws = new WebSocket("ws://" + document.location.host + "/audio");
var audio = document.getElementById("audio");
var chunks = [];
ws.onmessage = function(event) {
chunks.push(event.data);
var blob = new Blob(chunks);
audio.src = URL.createObjectURL(blob);
};
function startRecording() {
ws.send("start");
}
function stopRecording() {
ws.send("stop");
}
</script>
</body>
</html>
```
后端代码(Python):
```python
from flask import Flask, render_template, request, Response, jsonify
from flask_socketio import SocketIO
import pyaudio
import wave
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = None
frames = []
def start_stream():
global stream, frames
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
frames = []
while True:
data = stream.read(CHUNK)
frames.append(data)
if len(frames) > 10:
ws.send(b''.join(frames))
frames = []
@app.route('/')
def index():
return render_template('index.html')
@app.route('/audio')
def audio():
return Response(stream_audio(),
mimetype="audio/x-wav")
@socketio.on('connect')
def connect():
print('Client connected')
@socketio.on('disconnect')
def disconnect():
print('Client disconnected')
@socketio.on('message')
def message(message):
if message == 'start':
socketio.start_background_task(target=start_stream)
elif message == 'stop':
stream.stop_stream()
stream.close()
def stream_audio():
global stream, frames
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
output=True,
frames_per_buffer=CHUNK)
while True:
data = yield
stream.write(data)
if __name__ == '__main__':
socketio.run(app)
```
这个代码将使用 Flask 和 SocketIO 库来实现实时音频流传输。在前端,使用 WebSocket 与后端进行通信。当用户点击“Start Recording”按钮时,前端代码会向后端发送“start”消息,后端代码将启动一个新的线程来录制并传输音频。当用户点击“Stop Recording”按钮时,前端代码会向后端发送“stop”消息,后端代码将停止录制和传输音频。
在后端,使用 PyAudio 库来录制和播放音频。当一个新的客户端连接时,SocketIO 库将调用`connect`函数。当一个客户端断开连接时,SocketIO 库将调用`disconnect`函数。当收到来自客户端的消息时,SocketIO 库将调用`message`函数。如果消息是“start”,则将启动一个新的线程来录制和传输音频。如果消息是“stop”,则将停止录制和传输音频。`stream_audio`函数用于实际传输音频流。
请确保安装了 Flask、SocketIO 和 PyAudio 库。您可以使用以下命令来安装它们:
```python
pip install flask flask_socketio pyaudio
```
希望这可以帮助您实现所需的功能。
阅读全文