1var constraints = { audio: true };
2navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
3 var mediaRecorder = new MediaRecorder(mediaStream);
4 mediaRecorder.onstart = function(e) {
5 this.chunks = [];
6 };
7 mediaRecorder.ondataavailable = function(e) {
8 this.chunks.push(e.data);
9 };
10 mediaRecorder.onstop = function(e) {
11 var blob = new Blob(this.chunks, { 'type' : 'audio/ogg; codecs=opus' });
12 socket.emit('radio', blob);
13 };
14
15 // Start recording
16 mediaRecorder.start();
17
18 // Stop recording after 5 seconds and broadcast it to server
19 setTimeout(function() {
20 mediaRecorder.stop()
21 }, 5000);
22});
23
24// When the client receives a voice message it will play the sound
25socket.on('voice', function(arrayBuffer) {
26 var blob = new Blob([arrayBuffer], { 'type' : 'audio/ogg; codecs=opus' });
27 var audio = document.createElement('audio');
28 audio.src = window.URL.createObjectURL(blob);
29 audio.play();
30});