gpt4 book ai didi

javascript - 在现有的 HTML5 音频标签中播放 AudioBuffer

转载 作者:行者123 更新时间:2023-12-03 17:15:12 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Using local file as <audio> src

(2 个回答)


去年关闭。




我创建了一个网站,其中包含一个音频标签以及一个用于文件上传的工作放置区。

<body>
<audio id="myPlayer" controls>Your browser does not support the audio-tag</audio>
<div id="dropArea"></div>
</body>

拖动的音频文件然后被转换为 ArrayBuffer最终是 AudioBuffer .
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let arrayBuffer = await readFileAsArrayBuffer(audioFile);

audioContext.decodeAudioData(arrayBuffer, buf => {
console.log(buf);
});
AudioBuffer然后可以像这样在函数中播放:
playSound(buffer) => {
let source = context.createBufferSource();

source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}

以上所有工作都很好,但这不是我所追求的。

我想要 AudioBuffer改为在我的 HTML 的音频播放器中播放和控制。如何才能做到这一点?

最佳答案

回答我自己的问题,一个 data URL需要从上传的文件中创建。

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.


示例
// Helper Function
function readAsDataURL(file) {
return new Promise((resolve, reject) => {
if (file instanceof File) {
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(file);
} else {
reject(new Error("This type of object is not supported"));
}
});
}

// Set URL for audio player
(async () => {
const url = await readAsDataURL(event.dataTransfer.files[0]);
const audioElement = document.querySelector("#audio-player");

audioElement.src = url;
})();

关于javascript - 在现有的 HTML5 音频标签中播放 AudioBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com