[英]Display and play audio file selected in input JavaScript
I can't find how to play an audio file that the user has just selected with an input.我找不到如何播放用户刚刚通过输入选择的音频文件。 I have the following input :我有以下输入:
<input type='file' id="audio-input" class="audio-input" name="audio" accept=".mp3, .wav"/>
I would like display the audio file when the user select it so he can play it.我想在用户选择音频文件时显示音频文件,以便他可以播放。 It would be something like that :它会是这样的:
('#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());
});
I hope you understand what I'm trying to do, I don't really know how to explain it (maybe that's why I don't find any answers on other topics).我希望你明白我在做什么,我真的不知道如何解释它(也许这就是为什么我没有找到关于其他主题的任何答案)。
.val()
doesn't actually have the file you put into the input
. .val()
实际上没有您放入input
的文件。 You need to use its files
property.您需要使用它的files
属性。
Consider reading this MDN article that will demonstrate using files: Using files from web applications and this documentation on URL.createObjectURL()
which you need to use in order to provide your <audio>
with a src
.考虑阅读这篇将演示使用文件的 MDN 文章: 使用来自 Web 应用程序的文件和有关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>
有没有办法使用 css 属性编辑音频编辑栏(播放、滚动和音量栏)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.