javascript - 如何播放通过文件输入加载的音频
问题描述
我想通过输入文件阅读器加载音频文件,然后能够播放它......
以下是创建文件 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>
推荐阅读
- encryption - 端到端加密的额外数据操作
- cefsharp - 如何通过 CefSharp 进行整页搜索?
- processing - 越野弹跳球
- android - 如何获取数组列表
在 Glide 的帮助下作为输出? - c - valgrind - 地址是分配大小为 16 的块之前的 2 个字节
- javascript - Jquery 像史酷比一样滚动背景动画
- maven - 在maven中安装失败,但在IntelliJ中直接成功
- javascript - 隐藏右键时,中间引导按钮组中的圆角丢失
- ios - 高效的离屏 UIView 渲染和镜像
- python-3.x - 字符串比较不适用于 f.read()