我正在开发一个烧瓶项目。我希望用户能够在浏览器中记录他们的声音并将其发送到服务器。服务器不会处理或保存该数据,它只会回显数据。我的服务器端运行平稳,但是由于我没有太多经验,因此遇到了JavaScript问题。
我正在使用https://github.com/mattdiamond/Recorderjs来捕获用户数据并将其转换为wav文件,而不是将其发送到服务器。我无法将该二进制数据转换为wav文件,因此浏览器无法播放它。
注意:我愿意接受有关其他库的建议,对于上面凌乱的代码我很抱歉,我只是想使其首先工作。
客户端代码:
var socket = io();
socket.on('connect', function() {
});
var recorder;
let context;
var blob;
let audio = document.querySelector('audio');
let startBtn = document.querySelector('.record');
let stopBtn = document.querySelector('.stop');
let sendBtn = document.querySelector('.send');
window.URL = window.URL || window.webkitURL;
/**
* Detecte the correct AudioContext for the browser
* */
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
let onFail = function(e) {
alert('Error ' + e);
console.log('Rejected!', e);
};
function failed() {
console.log("recording failed");
}
let onSuccess = function(s) {
console.log('Recording...');
let tracks = s.getTracks();
startBtn.setAttribute('disabled', true);
stopBtn.removeAttribute('disabled');
context = new AudioContext();
let mediaStreamSource = context.createMediaStreamSource(s);
recorder = new Recorder(mediaStreamSource);
recorder.record();
stopBtn.addEventListener('click', () => {
console.log('Stop Recording...');
stopBtn.setAttribute('disabled', true);
startBtn.removeAttribute('disabled');
recorder.stop();
tracks.forEach(track => track.stop());
recorder.exportWAV(function(s) {
//audio.src = window.URL.createObjectURL(s);
socket.emit("sound", s);
});
});
}
startBtn.addEventListener('click', () => {
if (navigator.getUserMedia) {
/**
* ask permission of the user for use microphone or camera
*/
navigator.getUserMedia({ audio: true }, onSuccess, onFail);
} else {
console.warn('navigator.getUserMedia not present');
}
});
function callback() {
console.log("......");
}
sendBtn.addEventListener("click", () => {
console.log("get")
recorder.exportWAV(function(s) {
//audio.src = window.URL.createObjectURL(s);
socket.emit("sound", s); //sending to server
});
});
socket.on("sound-receive", data => { //this is where I try to do conversion
var element = document.querySelector(".message-container");
var aud = document.createElement("audio");
var reco = new Blob(data, { type: 'audio/wav' });
aud.src = window.URL.createObjectURL(reco);
element.appendChild(aud);
});