2

I have a game where I need background music playing and when I click a button it should play a sound. It plays the sound but stops the music.

The only way to turn the music back on is to have another event such as a button click. Is there any way to play a sound while the background music continues to play?

This is my code so far.

var a = new Audio("Latin Groove Hype App.mp3");

function init()
{  
    playBackGroundLoop();

}// in html(<body onload = "init()">)


function playSoundEffect()
{
    var playSoundCorrect = new Audio("Correct synth.mp3");
    playSoundCorrect.play();
}


function playBackGroundLoop()
{
    a.addEventListener('ended', function() 
                   {
                       this.currentTime = 0;
                       this.play();//plays music on loop
                   }, true);
    a.play();
}

$(function()
  {
  $("#playButton").on("click",function()
                {
                 playSoundEffect();
                }
  });

Thank you

4

1 に答える 1

0

ちょっと待って、あなたのプロジェクトに合うように私のスクリプトを渡してください:

HTML:

<ul id=nav>
    <li><a href="javascript:;">Item 1</a></li>
    <li><a href="javascript:;">Item 2</a></li>
</ul>

<audio id="audio-nav">
    <source src="click.mp3"></source>
    <source src="click.ogg"></source>
    Your browser isn't invited for super fun audio time.
</audio>
<audio id="audio-bg">
    <source src="bg.mp3"></source>
    <source src="bg.ogg"></source>
    Your browser isn't invited for super fun audio time.
</audio>

<a id="toggle" href="javascript:;">PLAY/PAUSE</a>

JS:

var bgMusic = $('#audio-bg')[0],
    navMusic = $('#audio-nav')[0],
    playing = true;

bgMusic.addEventListener('ended', function() {
    this.currentTime = 0;
    if (playing) {
        this.play();
    }
}, false);

bgMusic.play();

$('#toggle').click(function() {
    if (!bgMusic.paused) {
        bgMusic.pause();
        playing = false;
    } else {
        bgMusic.play();
        playing = true;
    }
});

$('#nav a').click(function() {
    navMusic.play();
});​

...そしてここに、完全に機能するデモがあります

于 2012-08-13T16:32:55.417 に答える