我使用this示例从设备麦克风捕获数据,但是我不知道如何将其转换为WAV文件以发送到服务器。
<script>
var handleSuccess = function(stream) {
var context = new AudioContext();
var source = context.createMediaStreamSource(stream);
var processor = context.createScriptProcessor(1024, 1, 1);
source.connect(processor);
processor.connect(context.destination);
processor.onaudioprocess = function(e) {
// Convert this to WAV and send to server
console.log(e.inputBuffer);
};
};
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(handleSuccess);
</script>
答案 0 :(得分:2)
synth-js
是我写的。
以下脚本将以Blob
的形式创建有效的WAV文件,其中包含音频的前5秒:
<script src="https://unpkg.com/synth-js/dst/synth.min.js"></script>
<script>
var handleSuccess = function(stream) {
var context = new AudioContext();
var source = context.createMediaStreamSource(stream);
var processor = context.createScriptProcessor(1024, 1, 1);
var data = [];
source.connect(processor);
processor.connect(context.destination);
processor.onaudioprocess = function(e) {
data.push.apply(data, e.inputBuffer.getChannelData(0));
// cut off after 5 seconds
if (data.length >= context.sampleRate * 5) {
context.close();
var track = stream.getAudioTracks()[0];
track.stop();
// Convert this to WAV
var wav = new synth.WAV(1, context.sampleRate, 16, true, data);
var blob = wav.toBlob();
// do something with blob
var src = URL.createObjectURL(blob);
var audio = new Audio();
audio.controls = true;
document.body.appendChild(audio);
// play back audio
audio.addEventListener('canplaythrough', function() { audio.play(); });
audio.src = src;
}
};
};
navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(handleSuccess);
</script>
您可以在JSFiddle上尝试此操作,因为堆栈片段不允许访问麦克风。
第var wav = new synth.WAV(1, context.sampleRate, 16, true, data);
行创建了一个新的WAV对象,该对象具有1个通道,采样率与输入匹配,WAV二进制文件中每个样本16位,采用小端格式(必需),并通过onaudioprocess
事件。