JS提取视频中的音频音轨并下载实例页面
回到相关文章 »效果:
1. 本地视频
2. 网络视频
//注意:需要允许跨域提供地址:https://imgservices-1252317822.image.myqcloud.com/coco/b12202023/67430f37.6y59kt.mp4
代码:
CSS代码:
.result:not(:empty) { border: 1px dashed darkgray; padding: 12px 16px; margin-top: 24px; }
HTML代码:
<h4>1. 本地视频</h4> <input type="file" id="file" accept="video/*"> <h4>2. 网络视频</h4> <input type="url" id="input" placeholder="在线视频地址"> <div id="result" class="result"></div>
JS代码:
const handleBuffer = function (buffer, name) { if (/\//.test(name)) { name = name.split('/').slice(-1)[0]; } name = name.split('.')[0]; // 创建音频上下文 const audioCtx = new AudioContext(); // arrayBuffer转audioBuffer audioCtx.decodeAudioData(buffer, function(audioBuffer) { // audioBuffer就是AudioBuffer const blob = bufferToWave(audioBuffer, audioBuffer.sampleRate * audioBuffer.duration); // 使用Blob地址 const blobUrl = URL.createObjectURL(blob); result.innerHTML = `<h4>试听</h4> <audio src="${blobUrl}" controls></audio> <p>点击<a href="${blobUrl}" download="${name}.wav">这里下载音频</a>。</p> `; }); }; // AudioBuffer转wav音频 function bufferToWave(abuffer, len) { // 见页面源码 } file.onchange = function (event) { const file = event.target.files[0]; // 开始识别 const reader = new FileReader(); reader.onload = function (event) { const arrBuffer = event.target.result; handleBuffer(arrBuffer, file.name); }; reader.readAsArrayBuffer(file); // 显示loading result.innerHTML = '<ui-loading></ui-loading>'; }; input.onchange = function () { result.innerHTML = '<ui-loading></ui-loading>'; fetch(url).then(res => res.arrayBuffer()).then(buffer => { handleBuffer(buffer, url); }); };