簡體   English   中英

無法在 html 中使用 js 播放音頻

[英]can not play audio with js in html

我寫了一些代碼來隨機播放一些音頻。但不起作用。請幫助我。 這是我的 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;
    }

和 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>

一方面,您正在設置play但從未使用它。 嘗試將第一行 `document.getEl...) 移動到設置播放后。 但總的來說,您的代碼有點混亂。 如果您願意,請嘗試這些進一步的更改:

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();

此外,有關什么是有效音頻 URL 和什么不是有效音頻 URL 的詳細信息,請參閱此 mdn 參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM