简体   繁体   中英

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:

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 :

 <!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. Try moving your first line `document.getEl...) to after you've set play. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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