Javascript在另一个启动时停止播放声音

时间:2017-04-15 20:22:06

标签: javascript

所以,在编码方面,我是一个完全的业余爱好者,但我仍然想摆弄它。 我目前正在制作一个基于html / jS / PHP的音板,我无法弄清楚如何在按下按钮播放另一个音乐时停止播放声音。

<script type="text/javascript" charset="utf-8">
        $(function() {
            $("audio").removeAttr("controls").each(function(i, audioElement) {
                var audio = $(this);
                var that = this; //closure to keep reference to current audio tag
                $("#doc").append($('<button>'+audio.attr("title")+'</button>').click(function() {
                    that.play();
                }));
            });
        });
    </script>

我希望有人理解这一点。提前致谢。 还有一个PHP代码可以自动从文件夹到前端获取音频文件,这可能是此问题的不必要信息。

4 个答案:

答案 0 :(得分:1)

如果您使用引入HTMLAudioElement的HTML5,这不是很难。

以下是您尝试执行的操作的最小代码:

// Let's create a soundboard module ("sb")
var sb = {
  song: null,
  init: function () {
    sb.song = new Audio();
    sb.listeners();
  },
  listeners: function () {
    $("button").click(sb.play);
  },
  play: function (e) {
    sb.song.src = e.target.value;
    sb.song.play();
  }
};

$(document).ready(sb.init);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Audio</title>
</head>
<body>
  <button value="https://www.gnu.org/music/FreeSWSong.ogg">Song #1</button>
  <button value="https://www.gnu.org/music/free-software-song-herzog.ogg">Song #2</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

您也可以考虑使用像howler.js这样的库来帮助您完成开发过程。

答案 1 :(得分:1)

您可以做的是,在开始播放新的音频暂停之前,页面上的所有可用音频。这样的事情。

var audioOne = document.querySelector('#audio-1');
var audioTwo = document.querySelector('#audio-2');

var allAudios = document.querySelectorAll('audio');

function stopAllAudio(){
	allAudios.forEach(function(audio){
		audio.pause();
	});
}

document.querySelector('#play-1').addEventListener('click', function(){
	stopAllAudio();
	audioOne.play();
})
document.querySelector('#play-2').addEventListener('click', function(){
	stopAllAudio();
	audioTwo.play();
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<audio id="audio-1"
  src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg">
</audio>
<audio id="audio-2"
  src="http://www.w3schools.com/html/horse.mp3">
</audio>

	<button id="play-1">
		play audio 1
	</button>
	<button id="play-2">
		play audio 2
	</button>	
</body>
</html>

您可以使用HTMLAudioElement

,而不是使用<audio>标记添加音频

答案 2 :(得分:0)

您可以stop and reset an audio element暂停并将当前时间设置为// Available sounds: const sounds = { "Bottle": "http://freewavesamples.com/files/Bottle.wav", "Bamboo": "http://freewavesamples.com/files/Bamboo.wav" } // Load audio elements: let audios = {}; for (let [title, url] of Object.entries(sounds)) { audios[title] = new Audio(url); } // Create board buttons: let board = document.getElementById("board"); for (let title of Object.keys(audios)) { let button = document.createElement("button"); button.textContent = title; button.dataset["audio"] = title; board.appendChild(button); } // Handle board button clicks: board.addEventListener("click", function(event) { let audio = audios[event.target.dataset["audio"]]; if (audio) { // Pause and reset all audio elements: for (let audio of Object.values(audios)) { audio.pause(); audio.currentTime = 0; } // Play this audio element: audio.play(); } });。只要单击一个按钮,您就需要这样做。例如:

&#13;
&#13;
<div id="board"></div>
&#13;
// Load buffer from 'url' calling 'cb' on complete:
function loadBuffer(url, cb) {
  var request = new XMLHttpRequest();
  request.open('GET', url);
  request.responseType = 'arraybuffer';
  request.onload = () => context.decodeAudioData(request.response, cb);
  request.send();
}

// Available sounds:
const sounds = {
  "Bottle": "url/to/bottle.wav",
  "Bamboo": "url/to/bamboo.wav"
};

let audioCtx = new (AudioContext || webkitAudioContext)(),
    board = document.getElementById("soundboard"),
    buffers = {},
    source;

// Load buffers:
for (let [title, url] of Object.entries(sounds)) {
  loadBuffer(url, buffer => buffers[title] = buffer);
}

// Create board buttons:
for (let title of Object.keys(sounds)) {
  let button = document.createElement("button");
  button.textContent = title;
  button.dataset["buffer"] = title;
  board.appendChild(button);
}

// Handle board button clicks:
board.addEventListener("click", function(event) {
  let buffer = buffers[event.target.dataset["buffer"]];
  if (buffer) {
    if (source) source.stop();
    source = audioCtx.createBufferSource();
    source.buffer = buffer;
    source.connect(audioCtx.destination);
    source.start();
  }
});
&#13;
&#13;
&#13;

如果您想充分利用Web Audio API的全部功能,您可能会开始构建类似于此的音板:

&#13;
&#13;
<div id="soundboard"></div>
&#13;
body {
  margin: 0;
}
#stripe {
    background-color: white;
    text-align: center;
    height: 50px;
    color: black;
}

button {
    border: none;
    background: none;
    text-transform: uppercase;
    height: 100%;
    font-weight: 700;
    color: black;
    letter-spacing: 1px;
    font-size: inherit;
    transition: all 0.3s;
    outline: none;
}

button:hover {
    color: white;
    background: black;
}

.selected {
    color: white;
    background: black;
}
&#13;
&#13;
&#13;

请注意,上面给出的声音网址必须位于同一个域中,或者在相同的源策略下可用(请参阅CORS标头)。

答案 3 :(得分:0)

下面的代码可以帮助其他人:

var audioMap = new Map();
var rappers = document.querySelectorAll('.rapper');
rappers.forEach(function(rapper){
    audioMap.set(rapper, new Audio());
    rapper.addEventListener('click', function(){
        var audio = new Audio($(this).data('audio'));
        audio.play();
        audioMap.set(this, audio);
        var current = audioMap.get(this);
        // console.log('get', current);
        audioMap.forEach(function(audio){
            if( audio != current ){
                audio.pause();
                audio.currentTime = 0;
            }
        });
    });
});