gpt4 book ai didi

javascript - 显示和播放在输入 JavaScript 中选择的音频文件

转载 作者:行者123 更新时间:2023-12-05 01:41:15 24 4
gpt4 key购买 nike

我找不到如何播放用户刚刚通过输入选择的音频文件。我有以下输入:

<input type='file' id="audio-input" class="audio-input" name="audio" accept=".mp3, .wav"/>

我想在用户选择音频文件时显示它,以便他可以播放。应该是这样的:

('#audio-input-0').change( function () {

let audio =
"<audio controls>" +
" <source id='audioFile' type='audio/mpeg'>" +
" Your browser does not support the audio element." +
"</audio>";

$('body').append(audio);

$('#audioFile').attr('src', $(this).val());
});

我希望你明白我想做什么,我真的不知道如何解释它(也许这就是为什么我在其他主题上找不到任何答案的原因)。

最佳答案

.val()实际上没有你放入 input 的文件.你需要使用它的 files 属性(property)。

考虑阅读这篇将演示如何使用文件的 MDN 文章:Using files from web applications以及关于 URL.createObjectURL() 的文档您需要使用它来提供您的 <audio>src .

function changeHandler({
target
}) {
// Make sure we have files to use
if (!target.files.length) return;

// Create a blob that we can use as an src for our audio element
const urlObj = URL.createObjectURL(target.files[0]);

// Create an audio element
const audio = document.createElement("audio");

// Clean up the URL Object after we are done with it
audio.addEventListener("load", () => {
URL.revokeObjectURL(urlObj);
});

// Append the audio element
document.body.appendChild(audio);

// Allow us to control the audio
audio.controls = "true";

// Set the src and start loading the audio from the file
audio.src = urlObj;
}

document
.getElementById("audio-upload")
.addEventListener("change", changeHandler);
<div><label for="audio-upload">Upload an audio file:</label></div>
<div><input id="audio-upload" type="file" /></div>

关于javascript - 显示和播放在输入 JavaScript 中选择的音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54932711/

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