Sample Sound Class

From WebOS101

Jump to: navigation, search

Create a models directory in app and create music.js with the following contents:

// Copyright (c) 2009 Roy Sutton - You may use this class with your applications
// Background music class for webOS
var Music = {
source: undefined,
 
setupMusic: function(src, repeat)
{
this.source = src;
audioObj = new Audio();
audioObj.addEventListener(Media.Event.X_PALM_CONNECT, this.audioIsReady.bind(this));
audioObj.addEventListener(Media.Event.X_PALM_DISCONNECT, this.audioIsGone);
if(repeat === true)
{
audioObj.addEventListener(Media.Event.ENDED, this.audioRepeat);
}
},
 
playMusic: function()
{
if(audioObj.src === this.source)
{
audioObj.play();
}
else
{
audioObj.src = this.source;
}
 
},
 
pauseMusic: function()
{
audioObj.pause();
},
 
audioIsReady: function(event)
{
if(Prefs.music)
{
event.target.src = this.source;
}
},
 
audioIsGone: function(event)
{
event.target.pause();
},
 
audioRepeat: function(event)
{
event.target.play();
}
};

Modify sources.js:

{"source": "/usr/palm/frameworks/media/Audio.js"},
{"source": "app/models/music.js"},

Add the following in your first scene's setup for this to be used as background music:

Mojo.Event.listen(document, Mojo.Event.stageDeactivate, this.pauseMusic.bind(this));
Mojo.Event.listen(document, Mojo.Event.stageActivate, this.resumeMusic.bind(this));
Music.setupMusic(Mojo.appPath+"/mysound.wav", true);

Then create the following:

MainAssistant.prototype.pauseMusic = function(event) {
Music.pauseMusic();
};
 
MainAssistant.prototype.resumeMusic = function(event) {
Music.playMusic();
};

Notes

  • This could be optimized a bit more and any comments are welcome.
  • Suggested improvements:
    • Add callback for sound done.
    • Add cache to allow for multiple sounds, reusing discarded sounds to prevent memory leaks

Useful Links

Personal tools