/
audio.py
47 lines (37 loc) · 1.42 KB
/
audio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Audio Recording Socket.IO Example
Implements server-side audio recording.
"""
import os
import uuid
import wave
from flask import Blueprint, current_app, session, url_for, render_template
from flask_socketio import emit
from socketio_examples import socketio
bp = Blueprint('audio', __name__, static_folder='static',
template_folder='templates')
@bp.route('/')
def index():
"""Return the client application."""
return render_template('audio/main.html')
@socketio.on('start-recording', namespace='/audio')
def start_recording(options):
"""Start recording audio from the client."""
id = uuid.uuid4().hex # server-side filename
session['wavename'] = id + '.wav'
wf = wave.open(current_app.config['FILEDIR'] + session['wavename'], 'wb')
wf.setnchannels(options.get('numChannels', 1))
wf.setsampwidth(options.get('bps', 16) // 8)
wf.setframerate(options.get('fps', 44100))
session['wavefile'] = wf
@socketio.on('write-audio', namespace='/audio')
def write_audio(data):
"""Write a chunk of audio from the client."""
session['wavefile'].writeframes(data)
@socketio.on('end-recording', namespace='/audio')
def end_recording():
"""Stop recording audio from the client."""
emit('add-wavefile', url_for('static',
filename='_files/' + session['wavename']))
session['wavefile'].close()
del session['wavefile']
del session['wavename']