EzDevInfo.com

SoundJS

A Javascript library for working with Audio. It provides a consistent API for loading and playing audio on different browsers and devices. Currently supports WebAudio, HTML5 Audio, Cordova / PhoneGap, and a Flash fallback.

Qooxdoo sound button on/off doesnt work

I catch button in the code: this.buttons.Sound.addListener("pressed", this.__sound, this);

And write function, but then I push button sound off/on they didn't work.

__sound: function(){
  if (this.buttons.Sound.isEnabled()){
     createjs.Sound.volume = 1;
   } else {
     createjs.Sound.volume = 0;
   }
},

Source: (StackOverflow)

Multiple instances of sound (SoundJS)

I'm using SoundJS to manage audio in a html5 game we're building. Simplified: we have a song playing in the background and a voice track playing at the same time.

I now would like to use an analyser on the voice track to animate one of the characters. We basically want to do a very rudimentary lipsync implementation.

However, since sound.js uses a single context (as it should), I'm unable to destinguish between music and voice. Therefor I was wondering if it was possible to start two instances of create.js sound (and thus have two seperate contexts, so I can analyse only the voice track).

Thanks! Thijs


Source: (StackOverflow)

Advertisements

How to get FlashPro CC HTML5 Canvas exports to work with sound on the iPad/iPhone

I can't get FlashPro CC HTML5 Canvas exports to work with sound on the iPad/iPhone. I reached out on Twitter and got this response:

"Timeline plays on click, but sound plays asynchronously on frame2. Fix this using "playEmptySound."

Here is the link I was given. http://www.createjs.com/Docs/SoundJS/classes/WebAudioPlugin.html#method_playEmptySound

OK, now the problem, I am an animator at best, and know very little if any codeā€¦ where do I insert this "playEmptySound" code?

I've posted the 2 files Flash kicks out, the HTML & the JS Any help on this will be greatly appreciated.

This is the JS animation generated from Flash CC

(function (lib, img, cjs) {

var p; // shortcut to reference prototypes

// library properties:
lib.properties = {
    width: 550,
    height: 400,
    fps: 15,
    color: "#FFFFFF",
    manifest: [
        {src:"audio/moo.mp3", id:"moo"}
    ]
};



// symbols:



(lib.triangle = function() {
    this.initialize();

    // Layer 1
    this.shape = new cjs.Shape();
    this.shape.graphics.f("#6600FF").s().p("AolIlIIJxKIJBRKg");
    this.shape.setTransform(55,55);

    this.addChild(this.shape);
}).prototype = p = new cjs.Container();
p.nominalBounds = new cjs.Rectangle(0,0,110,110);


(lib.square_btn = function() {
    this.initialize();

    // Layer 1
    this.shape = new cjs.Shape();
    this.shape.graphics.f("#FF0000").s().p("AnkHlIAAvJIPJAAIAAPJg");
    this.shape.setTransform(48.5,48.5);

    this.addChild(this.shape);
}).prototype = p = new cjs.Container();
p.nominalBounds = new cjs.Rectangle(0,0,97,97);


(lib.blue_btn = function(mode,startPosition,loop) {
    this.initialize(mode,startPosition,loop,{});

    // timeline functions:
    this.frame_2 = function() {
        playSound("moo");
    }

    // actions tween:
    this.timeline.addTween(cjs.Tween.get(this).wait(2).call(this.frame_2).wait(1));

    // Layer 1
    this.shape = new cjs.Shape();
    this.shape.graphics.f().s("#009900").ss(1,1,1).p("AGQAAQAAClh2B1Qh1B2ilAAQikAAh2h2Qh1h1AAilQAAikB1h2QB2h1CkAAQClAAB1B1QB2B2AACkg");
    this.shape.setTransform(40,40);

    this.shape_1 = new cjs.Shape();
    this.shape_1.graphics.f("#0066FD").s().p("AkaEaQh1h1AAilQAAikB1h2QB2h1CkAAQClAAB1B1QB2B2AACkQAAClh2B1Qh1B2ilAAQikAAh2h2g");
    this.shape_1.setTransform(40,40);

    this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.shape_1},{t:this.shape}]}).to({state:[{t:this.shape_1},{t:this.shape}]},2).wait(1));

}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-1,-1,82,82);


(lib.background = function() {
    this.initialize();

    // Layer 1
    this.shape = new cjs.Shape();
    this.shape.graphics.f("#666666").s().p("EgsXAgMMAAAhAXMBYvAAAMAAABAXg");
    this.shape.setTransform(284.1,206.1);

    this.addChild(this.shape);
}).prototype = p = new cjs.Container();
p.nominalBounds = new cjs.Rectangle(0,0,568.2,412.1);


(lib.sound_mc = function(mode,startPosition,loop) {
    this.initialize(mode,startPosition,loop,{});

    // timeline functions:
    this.frame_0 = function() {
        /* Stop at This Frame
        The  timeline will stop/pause at the frame where you insert this code.
        Can also be used to stop/pause the timeline of movieclips.
        */

        this.stop();

        /* Click to Go to Frame and Play
        Clicking on the specified symbol instance moves the playhead to the specified frame in the timeline and continues playback from that frame.
        Can be used on the main timeline or on movie clip timelines.

        Instructions:
        1. Replace the number 5 in the code below with the frame number you would like the playhead to move to when the symbol instance is clicked.
        2.Frame numbers in EaselJS start at 0 instead of 1
        */

        this.square_btn.addEventListener("click", fl_ClickToGoToAndPlayFromFrame_2.bind(this));

        function fl_ClickToGoToAndPlayFromFrame_2()
        {
            this.gotoAndPlay(1);
        }
    }
    this.frame_2 = function() {
        playSound("moo");
    }

    // actions tween:
    this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(2).call(this.frame_2).wait(58));

    // square
    this.square_btn = new lib.square_btn();
    this.square_btn.setTransform(48.5,48.5,1,1,0,0,0,48.5,48.5);
    new cjs.ButtonHelper(this.square_btn, 0, 1, 1);

    this.timeline.addTween(cjs.Tween.get(this.square_btn).to({y:210.5},33).wait(27));

}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(0,0,97,97);


// stage content:



(lib.moo_button = function(mode,startPosition,loop) {
    this.initialize(mode,startPosition,loop,{});

    // timeline functions:
    this.frame_0 = function() {
        /* Stop at This Frame
        The  timeline will stop/pause at the frame where you insert this code.
        Can also be used to stop/pause the timeline of movieclips.
        */

        this.stop();

        /* Click to Go to Frame and Play
        Clicking on the specified symbol instance moves the playhead to the specified frame in the timeline and continues playback from that frame.
        Can be used on the main timeline or on movie clip timelines.

        Instructions:
        1. Replace the number 5 in the code below with the frame number you would like the playhead to move to when the symbol instance is clicked.
        2.Frame numbers in EaselJS start at 0 instead of 1
        */

        this.blue_btn.addEventListener("click", fl_ClickToGoToAndPlayFromFrame.bind(this));

        function fl_ClickToGoToAndPlayFromFrame()
        {
            this.gotoAndPlay(1);
        }
    }

    // actions tween:
    this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(50));

    // Layer 2
    this.triangle = new lib.triangle();
    this.triangle.setTransform(377,178,1,1,0,0,0,55,55);

    this.timeline.addTween(cjs.Tween.get(this.triangle).wait(50));

    // Layer 1
    this.blue_btn = new lib.blue_btn();
    this.blue_btn.setTransform(85,203,1,1,0,0,0,40,40);
    new cjs.ButtonHelper(this.blue_btn, 0, 1, 2);

    this.timeline.addTween(cjs.Tween.get(this.blue_btn).to({x:455},49).wait(1));

    // Layer 4
    this.sound_mc = new lib.sound_mc();
    this.sound_mc.setTransform(220.6,84.5,1,1,0,0,0,48.5,48.5);

    this.timeline.addTween(cjs.Tween.get(this.sound_mc).wait(50));

    // Layer 3
    this.instance = new lib.background("synched",0);
    this.instance.setTransform(278.1,202.1,1,1,0,0,0,284.1,206.1);

    this.timeline.addTween(cjs.Tween.get(this.instance).wait(50));

}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(269,196,568.2,412.1);

})(lib = lib||{}, images = images||{}, createjs = createjs||{});
var lib, images, createjs;

This is the HTML generated from Flash CC

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>moo_button-tringle2</title>

<script src="script/easeljs-0.7.1.min.js"></script>
<script src="script/tweenjs-0.5.1.min.js"></script>
<script src="script/movieclip-0.7.1.min.js"></script>
<script src="script/preloadjs-0.4.1.min.js"></script>
<script src="script/soundjs-0.5.2.min.js"></script>
<script src="moo_button-tringle2.js"></script>

<script>
var canvas, stage, exportRoot;

function init() {
    canvas = document.getElementById("canvas");

    var loader = new createjs.LoadQueue(false);
    loader.installPlugin(createjs.Sound);
    loader.addEventListener("complete", handleComplete);
    loader.loadManifest(lib.properties.manifest);
}

function handleComplete() {
    exportRoot = new lib.moo_button();

    stage = new createjs.Stage(canvas);
    stage.addChild(exportRoot);
    stage.update();
    stage.enableMouseOver();

    createjs.Ticker.setFPS(lib.properties.fps);
    createjs.Ticker.addEventListener("tick", stage);
}

function playSound(id, loop) {
    createjs.Sound.play(id, createjs.Sound.INTERRUPT_EARLY, 0, 0, loop);
}
</script>
</head>

<body onload="init();" style="background-color:#D4D4D4">
    <canvas id="canvas" width="550" height="400" style="background-color:#FFFFFF"></canvas>
</body>
</html>

Source: (StackOverflow)

Leaving a webpage with SoundJS causes Google Chrome to crash

I have a webpage index.php which contains a link to sound.php. On sound.php, sound is played using SoundJS.

When I navigate from sound.php to index.php, Google Chrome usually (but not always) displays an error message ("Aw, Snap!"): https://support.google.com/chrome/answer/95669?hl=en

I'm using Chrome 40 for Mac OS. It doesn't matter whether I use a link or the browser's back button.

Here's my code:

sound.php calls a JS function that's using SoundJS:

<script type="text/javascript">      
  var int = [0, 7];
  prepareAudio();  
</script>

As soon as I delete this code, the browser doesn't crash anymore.

prepareAudio() is in an external file:

function prepareAudio() {   

  // Try WebAudio or HTMLAudio
  createjs.Sound.initializeDefaultPlugins();

  // Try flash otherwise
  if (!createjs.Sound.isReady()) {
    // Flash plug-in is not default
    createjs.FlashPlugin.swfPath = "../audio/";

    // Enable flash support
    $.getScript("../../js/flashplugin-0.6.0.min.js");

    // Prefer WebAudio over HTMLAudio. Prefer HTMLAudio over Flash.
    createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin, createjs.FlashPlugin]);
    }

  // Get audio files
  var audioPath = "../audio/";

  var manifest = [];
  for (var i = 0; i< audioFiles.length; i++)
    manifest.push({id: audioFiles[i], src: audioPath + audioFiles[i] + ".ogg"});

  // Play audio 
  var queue = new createjs.LoadQueue(); 
  createjs.Sound.alternateExtensions = ["mp3"];
  queue.installPlugin(createjs.Sound);
  queue.addEventListener("complete", function() {playTask(int);});
  queue.loadManifest(manifest);
  createjs.Sound.registerSounds(manifest, audioPath);
}

There's some more code involved. I play sounds using

  createjs.Sound.play(mySound); 

Audio playback is fine in Chrome and other browsers.


Source: (StackOverflow)

Mobile Safari crashes while loading just one 2mb audio file on iPhone 4s

I've stripped the problem right down to a few lines to isolate it. You can see it at http://radiorice.com/mobile/broken.html

The audio file is available in aac and ogg formats. It plays fine in mobile Safari when loaded inside an <audio> element. But when I try to register it in SoundJS, Safari crashes with the "A problem occurred with this webpage..." message.

The page works fine in desktop Safari, in Chrome and even in the version of mobile Safari I have running on an iPhone 4s in iOS simulator. There are no problems reported in the console for the simulator.

Because the crash is always about 10s after the page loads I wondered if it was a problem relating to the mobile Safari 10s time limit and tried putting the registerSound call in a timeout() function with a 10s delay. That simply delayed the crash by 10s.

I don't think this is a memory problem because the audio file can be loaded and played quite happily inside the <audio> tag.

<html>
<!DOCTYPE html>
<head>        
<script src="https://code.createjs.com/soundjs-0.6.0.min.js"></script>
    <script>
        var sounds =[
            {id:"Sleep_Talk_Recorder", src:"Sleep_Talk_Recorder.m4a"}
        ];
        createjs.Sound.initializeDefaultPlugins();
        createjs.Sound.alternateExtensions = ["ogg"];
        createjs.Sound.on("fileload", handleLoad); // call handleLoad when each sound loads
        createjs.Sound.registerSounds(sounds, "../content/sounds/small/");

        function handleLoad(event) {
        console.log("Preloaded:", event.id, event.src);
        }
    </script>
</head>
<body>
    <p>Audio file plays fine:</p>
    <audio controls>
    <source src="../content/sounds/small/Sleep_Talk_Recorder.m4a" type="audio/aac">
    <source src="../content/sounds/small/Sleep_Talk_Recorder.ogg" type="audio/ogg">
    Your browser does not support the audio element.
    </audio>
</body>
</html>

Source: (StackOverflow)

PreloadJS cannot find audio

I'm working on hobby project. I'm using createjs. But, of course, I have a problem. Since I update the code to use Preloadjs, the browser can no longer find the audio files. Here is my loading code:

function load (canvasToShowProgress) {
    canvas = canvasToShowProgress;
    loadingStage = new createjs.Stage();
    loadQueue = new createjs.LoadQueue(true);
    progessText = new createjs.Text("Loading... 0%");
    loadingStage.addChild(loadingStage);
    loadingStage.update();

    //start loading
    loadQueue.installPlugin(createjs.Sound);
    loadQueue.setMaxConnections(4); // Allow 4 concurrent loads
    loadQueue.loadManifest("configuration/GameAssets.json");
    loadQueue.on("progress", handleProgress);
    loadQueue.on("complete",handleComplete);
}

My manifest GameAssets.json looks like this:

{"manifest":
[   {"src":"images/game/street.png", "id":"street"},
    {"id":"Default", "src":"sounds/game/background.ogg"},
    {"id":"Psychic", "src":"sounds/game/ps.ogg"},
    {"id":"Nitro", "src":"sounds/game/ntr.ogg"}
]
}

By the way, the image is loaded perfectly. In the music player class, I call the audio by simply doing soundInstance = createjs.Sound.play(soundIds[currentPlayIndex]);. (The soundIds is temporary a hardcoded array with the ids. Where is my mistake?


Source: (StackOverflow)

How do I map a hotkey to a SoundJS sound effect?

I'm back again. Still learning javascript, still returning to Stack after a day of failing. Here we go.

So I want to be able to bind a keypress to a certain sound effect using SoundJS.

Here's the testing ground: http://nowthatsgenius.com/clients/beatbox/

There we're moments where I would have the keypress working, but it plays the same sound effect except mapping to the sound I want the keypress to map to. If you know of a solution, please explain as detail as you can since I'm a UI/UX designer first. Thanks!!!

Here's my code:

<body onload="init();">
    <section class="player-container">
        <article class="player-controls">
            <ul class="player-controls">
                <li class="player-controls-button" id="loop1" onclick="playLoop(this)">Loop 1</li>
                <li class="player-controls-button" id="loop2" onclick="playLoop(this)">Loop 2</li>
            </ul>
        </article>
    </section>
    <section class="mpc-container">
        <article class="mpc-title mpc-col">
            <span class="text">V1</span>
        </article>
        <article class="mpc-controls mpc-col">
            <ul class="mpc-controls-wrap">
                <li class="mpc-controls-row">
                    <ul>
                        <li class="mpc-controls-button" id="_q" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_w" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_e" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_r" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_t" onclick="playSound(this)"></li>

                        <li class="mpc-controls-button" id="_y" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_u" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_i" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_o" onclick="playSound(this)"></li>
                        <li class="mpc-controls-button" id="_p" onclick="playSound(this)"></li>
                    </ul>
                </li>
            </ul>
        </article>
    </section>

    <script src="assets/js/vendor/jquery-1.11.2.min.js"></script>
    <script src="assets/js/vendor/jquery.hotkeys.js"></script>
    <script src="assets/js/vendor/soundjs-0.6.0.min.js"></script>
    <script>

        var preload;
        var soundjs = createjs.Sound;

        function init(){
            if (!soundjs.initializeDefaultPlugins()) {
                document.getElementById("error").style.display = "block";
                document.getElementById("content").style.display = "none";
                return;
            }

            var assetsPath = "assets/";
        var sounds = [
                {id:"loop1", src:"loop1.mp3"},
                {id:"loop2", src:"loop2.mp3"},

            {id:"_q", src:"snare.wav"},
            {id:"_w", src:"kick1.wav"},
            {id:"_e", src:"clap1.wav"},
            {id:"_r", src:"closedhat.wav"},
            {id:"_t", src:"cymbal.wav"},
            {id:"_y", src:"kick2.wav"},
            {id:"_u", src:"clap2.wav"},
            {id:"_i", src:"openhat.wav"},
            {id:"_o", src:"voice1.wav"},
            {id:"_p", src:"voice2.wav"},
        ];

        soundjs.alternateExtensions = ["mp3"];  
        createjs.Sound.addEventListener("fileload", createjs.proxy(handleKey, this));
    createjs.Sound.registerSounds(sounds, assetsPath);
        soundjs.registerSounds(sounds, assetsPath);
      }

      var instance = null;

      function playSound(target) {
      instance = soundjs.play(target.id, soundjs.INTERRUPT_NONE);
      }

      var elements = [

          "q","w","e","r","t","y","u","i","o","p"

      ];

      function handleKey(event){

        // the fetching...
        $.each(elements, function(i, e) { // i is element index. e is element as text.
           var newElement = ( /[\+]+/.test(elements[i]) ) ? elements[i].replace("+","_") : elements[i];
           // Binding keys
           $(document).bind('keydown', elements[i], function assets() {
                playSound();
              $('#_'+ newElement).addClass('clicked');
              setTimeout(function(){$('#_'+ newElement).removeClass('clicked');},1000);

              return false;
           });

        });
      }

      var loop1 = null;
      var loop2 = null;

      function playLoop(target){

        // If loop1 exists, stop it and delete it
        if(loop1){
            loop1.stop();
            loop1 = null;
        }else if(target.id == "loop1"){
            loop1 = soundjs.play(target.id, soundjs.INTERRUPT_NONE);
        }

        // If loop2 exists, stop it and delete it
        if(loop2){
            loop2.stop();
            loop2 = null;
        }else if(target.id == "loop2"){
            loop2 = soundjs.play(target.id, soundjs.INTERRUPT_NONE);
        }
      }

      $(function(){
        $('.mpc-controls-button').on('click',function(){
            $(this).addClass('clicked');
            setTimeout(function(){
                $('.mpc-controls-button').removeClass('clicked');
            },1000);
        });
      });

    </script>

</body>

Source: (StackOverflow)

Where is the best place to download FlashAudioPlugin.swf when using SoundJS?

The file is required to use the Flash player in SoundJS (see here), but is not included in any of their downloadable builds.


Source: (StackOverflow)

Animated slides with EaselJS

I have multiple flash animations that need to be converted to HTML 5. I used Flash CC and it works fine. The thing is, I need them like a presentation: when one stops playing, there should be a button to load the next one and another to go back.

I was able to do it inserting the two .js files and calling the goTo() function with a div:

<script src="animation_01.js"></script>
<script src="animation_02.js"></script>
<script>
function goTo(slideN) {
    switch (slideN) {
        case 1:
            exportRoot = new lib.animation_01();
        break;
        case 2:
            exportRoot = new lib.animation_02();
        break;
    }

    stage.removeAllChildren();
    stage.addChild(exportRoot);
    stage.update();

    createjs.Ticker.setFPS(lib.properties.fps);
    createjs.Ticker.addEventListener("tick", stage);
}
</script>

The problem is: I will have to call each .js file and write a lot of cases for each animation... Is there a simpler way to do it?


Source: (StackOverflow)

playing audio with SoundJS in Intel XDK

I'm playing audio in my HTML5 app using:

createjs.Sound.play('boom-sound');

I then imported the project to Intel XDK. Now the game is playing smoothly in the emulator but the no sounds are there. I also tested after building the app for android and no audio was there.

Any idea, anyone?


Source: (StackOverflow)

Cocoonjs soundjs not playing on ios

We're building an html project using cocoonjs webview+, but soundjs doesn't play when we open our app on ios.

Everything works fine on android in webview+, and we've tried mp3, ogg, and m4v sound files with ios. Does anyone have any idea what we could try next.

This is applying to both autoplay sounds, and sounds that are triggered by user interaction (e.g. in onclick handlers).


Source: (StackOverflow)

Soundjs range input volume sliders in iOS

Is there a best practice for getting range-input sliders for volume to work in iOS? works fine on desktop but not so much in iOS. Some of the code may look odd but I've got multiple sliders controlling multiple intances on the page so this is what's working for now.

basically I call:

<input type="range" min="0" max="1" step="0.01"    value=".05" id="bg_2_gain" onmousedown="volAdjust(this)">

which then:

function volAdjust(target){ 
var id = $(target).closest('div.bg').attr('id');
T="#"+target.id;
var CurrentSI = mySounds[id];
$(T).on('input',function () { 
val=$(T).val();
CurrentSI.volume=val;
});
}

Source: (StackOverflow)

CreateJS - Issue loading sounds in IE11

I've run across a weird issue with sound file loading in IE11. I have a manifest of about a dozen images and then about 8 sound files. What's happening is versions of IE11 that have even the slightest modifications in the security settings are hanging up when trying to load the sound files. No errors, it just hangs. Any ideas?

Code below. Working fine in Chrome, Safari, FireFox and most IEs. Just some instances it loading everything up until the sounds and then it just stops.

var imagePath = "Game/images/";
var audioPath = "Game/sounds/";
manifest = [
    { src: imagePath + "BG.png", id: "bgImg" },
    { src: imagePath + "Game-Sign.png", id: "gameSign" },
    { src: imagePath + "Start-Title.png", id: "startTitle" },
    { src: imagePath + "Start-Button-Sprite.png", id: "btnStart" },
    { src: imagePath + "Continue-Button-Sprite.png", id: "btnContinue" },
    { src: audioPath + "clunk01.mp3", id: "sndClunk01" },
    { src: audioPath + "clunk02.mp3", id: "sndClunk02" },
    { src: audioPath + "clunk03.mp3", id: "sndClunk03" }
];

 var queue;
 queue = new createjs.LoadQueue(true);
 queue.installPlugin(createjs.Sound);
 createjs.Sound.alternateExtensions = ["ogg"];
 queue.addEventListener("complete", handleComplete);
 queue.loadManifest(manifest);

Source: (StackOverflow)

SoundJS music clips should toggle each other on/off

I have a bunch of sounds on a page, similar to the sound grid example. Some of these tracks are music tracks and I'd like to treat them differently. Most of the sounds can play over each other and that is the intent, however, no music track should be able to play over another music track. Think radio buttons.

I've got some very woolly code that detects if the other track is playing when clicked and stops the track, and switches that track's css (play icons and such). But now, adding a 3rd or 4th track to the mix becomes unruly.

sounds are loaded and stored in a hash of reusable sound instances that look like:

  mySounds["sound1"]= createjs.Sound.createInstance("sound1");
  ...

when the button in the html is clicked on (I'm not currently using the data-type attribute, that was from an earlier attempt but I thought it might be useful):

    <button type="button" class="btn btn-vol btn-sm" data-type="music" data-track="music1" onclick="play(this)">
    <span class="glyphicon glyphicon-play bplay"></span></button>

I currently do:

function play(target) {

    //define some stuff from html
    musicTrack = $(target).attr('data-track');
    music1 = $('button[data-track="music1"]');
    music2 = $('button[data-track="music2"]');
    myInstance = mySounds[id] //id is defined elsewhere

    toggle = $(target).find('span.bplay'); //this is where I have the play/pause icons

    //For all cases, not just music I find the play icon and swap it.
    if(toggle.hasClass('glyphicon-play')){ //the sound is ready to play. if it had a stop icon it would mean it was already playing

    toggle.removeClass('glyphicon-play');
    toggle.addClass('glyphicon-stop')

    //special case for music Tracks
    if(musicTrack == "music1") { //If I clicked on music track 1
        if(mySounds[musicTrack2].position !=0){ //if it isn't 0, it's playing!
            music2.find('span.bplay).removeClass('glyphicon-stop');
            music2.find('span.bplay').addClass('glyphicon-play');
            mySounds[musicTrack2].stop();
        }
        else {
            //do nothing because track 2 isn't playing
        }

    } else if (musicTrack=="music2"){ //If I clicked on music track 2
        if(mySounds[musicTrack2].position !=0){
            music1.find('span.bplay').removeClass('glyphicon-stop');
            music1.find('span.bplay').addClass('glyphicon-play');
            mySounds[musicTrack1].stop();
        }
        else {
            //do nothing because track 1 isn't playing
        }

        myInstance.play(); // play the clicked on instance 

    }
    else {
        //if the glyphicon does not say play (says stop) then we stop the sound etc..
        toggle.removeClass('glyphicon-stop');
        toggle.addClass('glyphicon-play');
        myInstance.stop();
    }
}

I haven't checked the above for syntax as I copied it by hand from my code, keeping only the relevant bits, but all this works. I click on music1, if music 2 isn't playing - it plays. If music 2 is playing, it stops music 2, switches it's stop icon to play and plays music 1. My actual code does some tweening of the sounds before it stops so they crossfade nicely.

I'm not a programmer but I'd love to be able to do this in a more efficient/elegant manner. Surely there is a way!


Source: (StackOverflow)

Soundjs not working in android phone

I developed a html5 game using the createjs library including easeljs, preloadjs and soundjs in intel xdk environment. I tested it on intel xdk emulator and everything works fine. Then, I built the apk file using the android option on intel xdk and exported it to my android mobile which has android 4.4 version. Unfortunately, the sound I added to the game using soundjs doesn't work. However, if I build the apk file using the android crosswalk option and test it on my mobile, the sound works fine. However, the side effect of this option is the apk file size becomes much bigger and I don't like that. I googled it a bit and found this approach (http://www.createjs.com/tutorials/Mobile%20Safe%20Approach/). I tested this approach both on intel xdk emulator and my mobile as well. It works fine on intel xdk but doesn't work on my mobile. It seems that only the crosswalk option works on android mobile but the others. The code I wrote using soundjs is added below. Does anybody know the reason why soundjs doesn't work on the android native browser. Thanks a lot in advance.

function preloadBgSound(){
var queue = new createjs.LoadQueue();
createjs.Sound.alternateExtensions = ["mp3"];
queue.installPlugin(createjs.Sound);
queue.addEventListener("fileload", playBgSound);
queue.loadFile({id:"bgSound", src:"asset/happy_adventure.ogg"});
}

function playBgSound(){
createjs.Sound.play("bgSound", {loop:-1});
}   

Source: (StackOverflow)