Clicking on each bird will play the appropriate song.
In this demo, the blue jay's audio is loaded using the preloaded static audio element in the
HTML.
This is why clicking on the blue jay will also trigger the audio element's controls to play.
The cardinal's audio is loaded dynamically and is not tied to any audio elements in the
HTML. This
is why clicking on the cardinal does not trigger the audio element to play, and the audio
element
can be played simultaneously with the audio played by clicking on the cardinal.
Creating an instance of the track, which the bird classes will hold an
instance
of.
Note that the cardinal is loading on demand, while the jay is loaded using a preloaded audio
element on the page.
constructor(options = {}) {
super(options);
...
this._red = new bird({
name: 'Red',
position: new hamonengine.math.vector2(xOffset, yOffset),
//Defer audio loading until later.
song: new hamonengine.audio.track({ src: '../content/media/red.ogg' })
});
this._jay = new bird({
name: 'Jay',
position: new hamonengine.math.vector2(xOffset + (this._red.size + xOffset), yOffset),
song: new hamonengine.audio.track({
//Statically loaded audio that references an audio element in the DOM.
audio: document.getElementById('preloaded-audio')
})
});
}
Load the tracks during the onloadResources event.
/**
* An internal event that occurs when attempting to load resources.
* @returns {object} a promise that the resource has loaded successfully.
*/
async onloadResources() {
...
const jayPromise = this._jay.song.load();
const redPromise = this._red.song.load();
...
await jayPromise;
await redPromise;
...
}
Using the HamonEngine's onMouseEvent & collision detection determine if the user has clicked
on the bird and play the track.
onMouseEvent(type, v, e, caller) {
const birds = [this._red, this._jay];
if (type === 'up') {
//Handle interaction for each bird.
for (let i = 0; i < birds.length; i++) {
//NOTE: This calls
birds[i].onInteract(v);
}
}
...
}
To start or stop a track use play & stop. It's best to determine if the track is playing
before stopping it.
async sing() {
if (this.song) {
if (this.song.isPlaying) {
await this.song.stop();
}
this.song.play();
}
}
onInteract(v) {
//Determine if a user clicks on the bird.
if (this.isOver(v)) {
this.sing();
...
}
...
}