JavaScript 计算音频时长
1. 使用Audio获取duration
let audioUrl;
let duration = 0;
const processDuration = (blob: Blob) => {
const reader = new FileReader();
reader.onloadend = e => {
audioUrl = reader.result as string;
var media = new Audio(reader.result as string);
media.onloadedmetadata = function() {
if (media.duration != Infinity) {
duration = media.duration;
}
};
};
reader.readAsDataURL(blob);
};
但这个方法在Chrome上会存在bug,可能会计算duration为Infinity。可以尝试用下面方法解决。
2. 直接获取audiobuffer的duration
audioBuffer.duration
3. 用arraybuffer计算duration
如果获取的是纯pcm数据的arraybuffer,且知道audio的samplerate,计算$$duration = arraybuffer.bytelength / sampleRate / 2$$