繁体   English   中英

如何播放通过文件输入加载的音频

[英]How to play audio loaded via file input

我想通过输入文件阅读器加载音频文件,然后能够播放它...

以下是创建文件 blob 并将音频源分配给此 blob 的过程:

    fileInput.on('change', readFile);

    function readFile(e) {
        const input = e.target;
        if(input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const binaryData = e.target.result;
                const binary = convertDataURIToBinary(binaryData); 
                const blob = new Blob(binary, {type: input.files[0].type });
                console.log('inserting blobXX', blob);
                recordedAudioComponent.src = URL.createObjectURL(blob);             
                data.instructAudios[component] = blob;
                console.log('recordedAudioComponent.src', recordedAudioComponent.src);
            
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

这是上面代码在控制台上的结果:

在此处输入图片说明

现在我正在尝试播放recordedAudioComponent ,它是一个带有源的音频标签吗?

const recordedAudioComponent = document.getElementById(`recordedAudio-instruct-${component}`);
console.log(recordedAudioComponent)
recordedAudioComponent.play();

这是它产生的错误:

在此处输入图片说明

我该如何解决这个问题并播放音频?

编辑:这是在第一个代码中获取 blob 的函数:

   var BASE64_MARKER = ';base64,';

    function convertDataURIToBinary(dataURI) {
      var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
      var base64 = dataURI.substring(base64Index);
      var raw = window.atob(base64);
      var rawLength = raw.length;
      var array = new Uint8Array(new ArrayBuffer(rawLength));

      for(i = 0; i < rawLength; i++) {
        array[i] = raw.charCodeAt(i);
      }
      return array;
    }

您不需要任何转换,blob 实际上与文件本身非常相似,并且 URL.createObjectURL 方法接受文件作为参数,从浏览器播放音频文件所需要做的就是将 src 属性设置为 url创建,是这样的:

 <body> <input style="display: block;" type="file" onchange="loadAudioFile(this)"> <audio src=" " id="track" controls> </audio> <script> function loadAudioFile(e) { const url = URL.createObjectURL(e.files[0]); document.getElementById('track').setAttribute('src', url); } </script> </body>

<input type="file" name="fileInput" id="fileInput">
<script>
    const fileInput = document.querySelector('#fileInput');
    fileInput.onchange = readFile;

    /** @type {AudioNode} */
    const audio = document.createElement( 'audio' );

    function readFile(e) {
        const input = e.target;
        if(input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onloadend = function (e){
                audio.src = e.target.result;
                audio.play();
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
</body>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM