簡體   English   中英

HTML5 / Javascript一次只能播放一個音頻樣本

[英]HTML5/Javascript to only play one audio sample at a time

我有以下代碼,允許我按下按鈕並播放和音頻樣本。 它在這方面起作用,但是,當我按不同的按鈕時,音符會重疊,但是我希望按一個按鈕來停止播放先前的音符,並且只播放與最近按按鈕有關的聲音。 我該如何實現?

<!DOCTYPE html>


<script>

var e = new Audio('/Users/username/Downloads/e-note.mp3');
var d = new Audio('/Users/username/Downloads/d-note.mp3');
var g = new Audio('/Users/username/Downloads/g-note.mp3');

function play (note){

note.pause();
note.currentTime = 0;
note.play();

}

</script>

<button onclick="play(e)"> Click Me </button>
<button onclick="play(d)"> Click Me </button>
<button onclick="play(g)"> Click Me </button>
</html>

的HTML

<audio id="audio1">
    <source src="alarm.mp3" type="audio/mpeg" />
</audio>

Java腳本

var myAudio1 = document.getElementById("audio1");
myAudio1.play();

這就是我最終所做的工作。 我不知道是否有更有效的方法。

<!DOCTYPE html>


<script>

var e = new Audio('/Downloads/e-note.mp3');

var b = new Audio('/Downloads/b-note.mp3');
var g = new Audio('/Downloads/g-note.mp3');
var d = new Audio('/Downloads/d-note.mp3');
var a = new Audio('/Downloads/a-note.mp3');
var el = new Audio('/Downloads/elow-note.mp3');

    function play (note){

if (note==e) { 
b.pause(); g.pause(); d.pause(); a.pause(); el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.currentTime = 0;
note.play();
} 


if (note==b) {
e.pause();g.pause();d.pause();a.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==g) {
e.pause(); d.pause();b.pause();a.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==d) {
e.pause(); g.pause();b.pause();a.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==a) {
e.pause(); d.pause();b.pause();g.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==el) {
e.pause(); d.pause();b.pause();g.pause();a.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

}


</script>

<button onclick="play(e)"> E </button>
<button onclick="play(b)"> B </button>
<button onclick="play(g)"> G </button>
<button onclick="play(d)"> D </button>
<button onclick="play(a)"> A </button>
<button onclick="play(el)"> E </button>


</html>

暫無
暫無

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

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