JS的音频停止功能

时间:2019-04-01 20:42:04

标签: javascript html5 audio

我一直在尝试为自己制作的音板制作一个停止按钮,但是,即使我定义了Uncaught TypeError: audio.pause is not a function at Stop (test2.html:205) at HTMLButtonElement.onclick (test2.html:113),控制台也一直说audio。 (我删去了很多不必要的行)

我确保我已经正确拼写并正确装入了所有东西。

<html>
<head>
</head>
<button onclick="Kommunizm()">Kommunizm</button>
<button onclick="Lenin()">Lenin</button>
<button onclick="OurGame()">Our Game</button>
<button onclick="USSR()">USSR</button>
<button onclick="Stop()">Stop (But do you really want to?)</button>
<button id="About">About</button>

<script>
var audio;
var music = [
"Soviet_Union_national_anthem_(instrumental),_1977.oga",
"Internationale_orchestral_arrangement.ogg",
"Korobeiniki.ogg",
"y2mate.com - ussr_ymca_parody_YV2WuSJ9GcA_320kbps.ogg"
];

//Now why is this disobeying my command?
function Stop() {
for (i=0;i<music.length;i++){
audio = "audio" + i; 
audio.pause();
audio.currentTime = 0;
}
}

function Kommunizm(){
audio0 = new Audio(music[0]);
audio0.play();
}

function Lenin(){
audio1 = new Audio(music[1]);
audio1.play();
}

function OurGame(){
audio2 = new Audio(music[2]);
audio2.play();
}

function USSR(){
audio3 = new Audio(music[3]);
audio3.play();
}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

根据我的评论,我整理了一个快速的示例,该示例基于一些JSON构建的通用音板。这应该满足您的所有要求,并使您的生活更轻松。如果您不了解某事的工作方式或原因,请让我知道,不胜其烦。

const sounds = [
	{name: 'Kommunizm', location: 'Soviet_Union_national_anthem_(instrumental),_1977.oga'},
  {name: 'Lenin', location: 'Internationale_orchestral_arrangement.ogg'},
  {name: 'OurGame', location: 'Korobeiniki.ogg'},
  {name: 'USSR', location: 'y2mate.com - ussr_ymca_parody_YV2WuSJ9GcA_320kbps.ogg'}
];

const container = document.getElementById('button_container');
sounds.forEach(function(sound){
	let btn = document.createElement('button');
  btn.setAttribute('type', 'button')
  btn.setAttribute('data-source', sound.location);
  btn.setAttribute('data-name', sound.name);
  btn.innerHTML = sound.name;
  btn.addEventListener("click", playSound)
  container.appendChild(btn)
  
  let audio = document.createElement('audio');
  audio.setAttribute('id', sound.name);
  audio.setAttribute('autoplay', false);
  audio.setAttribute('src', sound.location);
  container.appendChild(audio);
});

function stop(){
  [].forEach.call(document.querySelectorAll('audio'), function(aud) {
    aud.stop();
  });
}

function playSound(){
	let player = document.getElementById(this.getAttribute('data-name'));
  if (player)
  	player.play();
}
<div id="button_container">

</div>
<button type="button" onclick="stop">
Stop All Sounds
</button>