首页 > 解决方案 > 如何播放通过文件输入加载的音频

问题描述

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

以下是创建文件 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;
    }

标签: javascriptjquery

解决方案


您不需要任何转换,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>


推荐阅读