簡體   English   中英

單擊 HTML 按鈕時嘗試播放聲音

[英]Trying to play a sound when HTML button is clicked

我對 web 開發相當陌生,我認為使用按鈕播放聲音將是一個足夠簡單的項目。 我首先嘗試關注一個在線視頻,該視頻在 html 頭部中使用了 javascript,看起來像<script> var myaudio= new Audio() and myaudio.src="go.wav" </script>並且按鈕上有onmousedown="myaudio.play()"作為屬性。

我嘗試的第二種方法來自這里的一個問題,它沒有使用 js,而只是使用 HTML5。 在我的文檔中,我有<audio id="myaudio" src="go.wav"> </audio>並且在按鈕上我有onmousedown='document.getElementId('myaudio').play()"作為屬性這些方法中的一個會導致聲音播放。我將聲音文件與我的項目文件放在同一個文件夾中。就像我說的,我是這個特殊東西的新手,我根本沒有使用過 Javascript。我想這會需要一些 js,這將是一個不錯的起點。提前致謝!

編輯:這是我的最小代碼由於我無法解決的格式問題,它不會讓我在這里輸入我的第一次嘗試,但唯一的區別是有<script> var myaudio= new Audio() and myaudio.src="go.wav" </script>在頭部和按鈕上我有onmousedown="myaudio.play()"作為屬性

    <html>
        <head>
            <title> Ready Go Trainer </title>
            <audio id="myaudio" src="go.wav"> </audio>
        </head>

        <body>

            <button type="button" class="but" onmousedown="document.getElementById('myaudio').play()"> start </button>

        </body>
    </html>

嘗試以下兩種方法之一:

解決方案 1

function playSound() {
    var audio = document.getElementById('audio');
    audio.play();
}

<button onclick="playSound()">Play Sound</button>
<audio id="audio" src="./path/to/sound"></audio>

解決方案 2

function playSound(soundFile) {
  new Audio(soundFile).play();
}

<button onclick="playSound('./path/to/sound')">Play Sound</button>

暫無
暫無

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

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