简体   繁体   English

无法在 html 中使用 js 播放音频

[英]can not play audio with js in html

I wrote some code for random playing of some audios.but does not work.please help me.我写了一些代码来随机播放一些音频。但不起作用。请帮助我。 here is my js file (N.js) that randomly choose an audio and set it to the realted elem:这是我的 js 文件 (N.js),它随机选择一个音频并将其设置为 realted elem:

var x = document.getElementById("pl").value  = play ;
var play ;
const a1 = new Audio('078.mp3');
const a2 = new Audio('079.mp3');
const a3 = new Audio('080.mp3');
const a4 = new Audio('063.mp3');
const a5 = new Audio('072.mp3');
function main() {
   var n = Math.floor((0) + 4);
   return n;}
   y=main();
    switch (y) {
        case 0 : play=a1;
        case 1 : play=a2;
        case 2 : play=a3;
        case 3 : play=a4;
        case 4 : play=a5;
    }

and the html file :和 html 文件:

 <!DOCTYPE html> <html lang="fa"> <script src="N.js"></script> <audio controls> <source id="pl" src=play type="audio/mp3"> </audio> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <strong>something</strong> </body> </html>

For one thing, you're setting play but never using it.一方面,您正在设置play但从未使用它。 Try moving your first line `document.getEl...) to after you've set play.尝试将第一行 `document.getEl...) 移动到设置播放后。 In general though, your code is a bit of a mess.但总的来说,您的代码有点混乱。 Try these further changes if you like:如果您愿意,请尝试这些进一步的更改:

let audioFiles = [
  '078.mp3',
  '079.mp3',
  '080.mp3',
  '063.mp3',
  '072.mp3',
];

let randomI = Math.floor(Math.random() * audioFiles.length);
let audio = new Audio(audioFiles[randomI]);

document.getElementById("pl").appendChild(audio);
audio.play();

Also, see this mdn reference for details on what is and is not a valid audio URL.此外,有关什么是有效音频 URL 和什么不是有效音频 URL 的详细信息,请参阅此 mdn 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM