提交按钮单击时随机音频(js)

7dl7o3gd  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(419)

我想创建一个提交按钮,当你每次点击它时,它会播放一个随机的音频文件。
有没有一种使用html/js的快速方法?

ercv8c1e

ercv8c1e1#

<!doctype html>
    <html>
      <head>
        <title>PlayAudio</title>
      </head>
      <body>

        <script>
          function playAudio() {
            var audio = document.getElementById("MySound");
            audio.play();
          }
        </script>

        <input type="button" value="Play Audio" onclick="playAudio()">
        <audio id="MySound" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>

      </body>
    </html>
r1wp621o

r1wp621o2#

假设您有一个包含如下文件的项目:项目文件
然后,您可以在html&js代码中这样做,以便在单击submit按钮时随机播放声音:

//Load the sound files into an array
const audioArr = [
    new Audio('audio/audio1.ogg'),
    new Audio('audio/audio2.ogg'),
    new Audio('audio/audio3.ogg'),
    new Audio('audio/audio4.ogg'),
    new Audio('audio/audio5.ogg'),
    new Audio('audio/audio6.ogg')
];

function playRandomAudio(){
    //Get a random index of the sound to be played
    const randomAudioIndex = Math.floor(Math.random() * (audioArr.length+1));

    //Play the selected sound
    audioArr[randomAudioIndex].play();
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>

<input type="submit" value="Submit" onclick="playRandomAudio()">

<script src="test_sound.js"></script>
</body>
</html>

希望这能回答你的问题。🙏

相关问题