簡體   English   中英

Javascript-第二個onclick音頻播放不起作用

[英]Javascript - Second onclick audio play does not work

我的腳本在播放音頻onclick時遇到問題。 我一次只能播放一個音頻.add.remove ),但不能播放第二個按鈕的聲音。

一次只能使用一個按鈕。

我在這里做錯了什么...?

提前致謝!

<button class="add">ADD TO CART</button>

<button class="remove">REMOVE</button>

//----------------

var audioAdd=new Audio('add.mp3');
$('.add').click(()=>audioAdd.play()
);

var audioRemove=new Audio('remove.mp3');
$('.remove').click(()=>audioRemove.play()
);

//----------------

// For test:

/*

https://notificationsounds.com/soundfiles/8b16ebc056e613024c057be590b542eb/file-sounds-1113-unconvinced.mp3

https://notificationsounds.com/soundfiles/99c5e07b4d5de9d18c350cdf64c5aa3d/file-sounds-1110-stairs.mp3

*/

由於之前的播放過程仍在進行中,因此連續點擊將不起作用。 您不能同時播放單個實例。 您必須等待播放過程完成。

你可以做這樣的事情

let audioHolder = {};

$('.add').click(()=>{
  let tempIdentifier = Date.now();
  audioHolder[tempIdentifier] = new Audio('add.mp3');
  audioHolder[tempIdentifier].play();

  // removing after play process gets over so if won't consume memory
  setTimeout(() => {
    delete audioHolder[tempIdentifier];
  }, audioHolder[tempIdentifier].duration + 400 /* you can remove threshold value if you wants to */);
});

// audioHolder[tempIdentifier].duration gives audio duration
// and adding some threshold so
// it will delete after it's played ( just to be safe )

/* same for other click */

這將適用於每次點擊

暫無
暫無

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

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