由于最近接到一个需求,需要通过前端技术提取视频内音乐,因此我们需要使用js将mp4格式转为mp3。
首先我们需要提取mp4内音频文件,使用AudioContext音频对象,将mp4内音频文件用wav格式导出。(前提是获取到视频的blob对象,blob对象可通过下载链接获取或直接上传文件提取)
export const bufferToWavBlob = (buffer: any, fileName: string, total: number, cd: any) => {
// 创建音频上下文
const audioCtx = new AudioContext();
// arrayBuffer转audioBuffer
audioCtx.decodeAudioData(buffer, async function (audioBuffer) {
// 提取音乐内的wavblob
const blob = bufferToWav(audioBuffer, audioBuffer.sampleRate * audioBuffer.duration);
});
}
function bufferToWav(abuffer, len) {
var numOfChan = abuffer.numberOfChannels,
length = len * numOfChan * 2 + 44,
buffer = new ArrayBuffer(length),
view = new DataView(buffer),
channels = [], i, sample,
offset = 0,
pos = 0;
// write WAVE header
// "RIFF"
setUint32(0x46464952);
// file length - 8
setUint32(length - 8);
// "WAVE"
setUint32(0x45564157);
// "fmt " chunk
setUint32(0x20746d66);
// length = 16
setUint32(16);
// PCM (uncompressed)
setUint16(1);
setUint16(numOfChan);
setUint32(abuffer.sampleRate);
// avg. bytes/sec
setUint32(abuffer.sampleRate * 2 * numOfChan);
// block-align
setUint16(numOfChan * 2);
// 16-bit (hardcoded in this demo)
setUint16(16);
// "data" - chunk
setUint32(0x61746164);
//