-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremote_mic_server.py
More file actions
199 lines (176 loc) · 6.9 KB
/
Copy pathremote_mic_server.py
File metadata and controls
199 lines (176 loc) · 6.9 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
from flask import Flask, render_template_string, send_from_directory
from flask_socketio import SocketIO, emit
import speech_recognition as sr
import base64
import os
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins='*')
# Initialize the recognizer
recognizer = sr.Recognizer()
recognizer.energy_threshold = 4000
# HTML template for the mobile interface
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
<title>Remote Microphone</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
text-align: center;
background-color: #f0f0f0;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: white;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.status {
margin: 20px 0;
padding: 10px;
border-radius: 5px;
}
.connected { background-color: #d4edda; color: #155724; }
.disconnected { background-color: #f8d7da; color: #721c24; }
.recording { background-color: #fff3cd; color: #856404; }
button {
background-color: #007bff;
color: white;
border: none;
padding: 15px 30px;
border-radius: 25px;
font-size: 16px;
cursor: pointer;
margin: 10px;
transition: background-color 0.3s;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
button:hover:not(:disabled) {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<h1>Remote Microphone</h1>
<div id="status" class="status disconnected">Disconnected</div>
<button id="startBtn" onclick="startRecording()" disabled>Start Recording</button>
<button id="stopBtn" onclick="stopRecording()" disabled>Stop Recording</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script>
let socket = io();
let mediaRecorder;
let audioChunks = [];
let isRecording = false;
socket.on('connect', () => {
document.getElementById('status').className = 'status connected';
document.getElementById('status').textContent = 'Connected';
document.getElementById('startBtn').disabled = false;
});
socket.on('disconnect', () => {
document.getElementById('status').className = 'status disconnected';
document.getElementById('status').textContent = 'Disconnected';
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = true;
});
async function startRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = (event) => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const reader = new FileReader();
reader.readAsDataURL(audioBlob);
reader.onloadend = () => {
const base64Audio = reader.result.split(',')[1];
socket.emit('audio_data', { audio_data: base64Audio });
};
};
mediaRecorder.start();
isRecording = true;
document.getElementById('status').className = 'status recording';
document.getElementById('status').textContent = 'Recording...';
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
// Automatically stop recording after 5 seconds
setTimeout(() => {
if (isRecording) {
stopRecording();
}
}, 5000);
} catch (err) {
console.error('Error accessing microphone:', err);
alert('Error accessing microphone. Please ensure microphone permissions are granted.');
}
}
function stopRecording() {
if (mediaRecorder && isRecording) {
mediaRecorder.stop();
isRecording = false;
document.getElementById('status').className = 'status connected';
document.getElementById('status').textContent = 'Connected';
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
}
}
socket.on('command_processed', (data) => {
console.log('Command processed:', data.command);
});
</script>
</body>
</html>
'''
@app.route('/')
def index():
return render_template_string(HTML_TEMPLATE)
@socketio.on('connect')
def handle_connect():
print('Client connected')
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected')
@socketio.on('audio_data')
def handle_audio_data(data):
try:
# Decode the base64 audio data
audio_data = base64.b64decode(data['audio_data'])
# Save the audio data to a temporary file
temp_file = 'temp_audio.wav'
with open(temp_file, 'wb') as f:
f.write(audio_data)
# Process the audio file with speech recognition
with sr.AudioFile(temp_file) as source:
audio = recognizer.record(source)
try:
command = recognizer.recognize_google(audio).lower()
print(f'Recognized command: {command}')
emit('command_processed', {'command': command, 'status': 'success'})
except sr.UnknownValueError:
print('Could not understand audio')
emit('command_processed', {'status': 'error', 'message': 'Could not understand audio'})
except sr.RequestError as e:
print(f'Could not request results: {e}')
emit('command_processed', {'status': 'error', 'message': f'Could not request results: {e}'})
# Clean up the temporary file
if os.path.exists(temp_file):
os.remove(temp_file)
except Exception as e:
print(f'Error processing audio: {e}')
emit('command_processed', {'status': 'error', 'message': str(e)})
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000, debug=True)