用JavaScript写用麦克风采集音频并将音频转换格式为16k16bits单声道音频,再转为blob传输给后端的代码
时间: 2023-03-23 14:00:39 浏览: 195
以下是使用JavaScript采集音频并将音频转换格式为16k16bits单声道音频并将其转换为blob的示例代码:
```javascript
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const bufferSize = 2048;
const recordingTime = 5000;
let audioData = [];
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
const mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
const audioChunks = [];
mediaRecorder.addEventListener("dataavailable", event => {
audioChunks.push(event.data);
});
setTimeout(() => {
mediaRecorder.stop();
stream.getTracks().forEach(track => track.stop());
const audioBlob = new Blob(audioChunks);
const reader = new FileReader();
reader.readAsArrayBuffer(audioBlob);
reader.onloadend = () => {
audioContext.decodeAudioData(reader.result, (buffer) => {
const audioBuffer = convertBuffer(buffer);
const audioBlob = bufferToBlob(audioBuffer);
sendBlobToServer(audioBlob);
});
};
}, recordingTime);
});
function convertBuffer(buffer) {
const sampleRate = buffer.sampleRate;
const numberOfChannels = buffer.numberOfChannels;
const length = buffer.length;
const newBuffer = audioContext.createBuffer(1, length, sampleRate);
const newChannel = newBuffer.getChannelData(0);
for (let i = 0; i < length; i++) {
let channelSum = 0;
for (let j = 0; j < numberOfChannels; j++) {
channelSum += buffer.getChannelData(j)[i];
}
newChannel[i] = channelSum / numberOfChannels;
}
return newBuffer;
}
function bufferToBlob(buffer) {
const numberOfChannels = buffer.numberOfChannels;
const length = buffer.length;
const newBuffer = new ArrayBuffer(length * numberOfChannels * 2);
const newView = new DataView(newBuffer);
for (let i = 0; i < length; i++) {
let offset = i * numberOfChannels * 2;
for (let j = 0; j < numberOfChannels; j++) {
let sample = Math.max(-1, Math.min(1, buffer.getChannelData(j)[i]));
sample = (sample + 1) / 2 * 65535;
newView.setInt16(offset, sample, true);
offset += 2;
}
}
return new Blob([newView], { type: "audio/wav" });
}
function sendBlobToServer(blob) {
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload-audio", true);
xhr.setRequestHeader("Content-Type", "audio/wav");
xhr.send(blob);
}
```
此代码通过调用Web API中的`getUserMedia`方法来获取音频流,使用`MediaRecorder`对象来记录音频数据,然后将记录的音频数据转换为blob,并使用`FileReader`对象将其读入内存中。然后,使用`decodeAudioData`方法将Blob数据解码为音频缓冲区,然后使用`convertBuffer`函数将音频缓冲区转换为单声道的16k16bits音频缓冲区,最后将缓冲区转换为Blob并发送到后端。
请注意,此示例代码仅用于参考。实际应用中可能需要根据具体需求进行修改。
阅读全文