flashup
December 15, 2017, 10:55am
#1
Hello. I want to load and play music files asynchronously in my app. Is it possible?
I have next section in project.xml:
<assets path="Assets/sounds/music" rename="assets/music" type="music" embed="false" include="*.mp3" />
And i load and play music like that:
Assets.loadSound(path, false).onComplete(onMusicLoaded);
function onMusicLoaded(sound:Sound) {
_channel = sound.play(0, 1000000, soundTransform);
}
It works well, but player should wait while whole file will be loaded.
I tried to load sound asynchronously directly with Sound instance:
var sound:Sound = new Sound();
var req:URLRequest = new URLRequest(path);
var context:SoundLoaderContext = new SoundLoaderContext(1000, false);
sound.load(req, context);
onMusicLoaded(sound);
But it didn’t work…
You could try this pull request:
…or maybe there is a good way to do streaming audio with howler.js
flashup
December 16, 2017, 4:48pm
#3
Yeah, good idea! I’ve done it with howler.js api
Would you mind sharing some of your code, to know how you implemented it? May come in handy with wiring official support in
Thanks
flashup
December 18, 2017, 7:49pm
#5
Sure!
Briefly, i just created 3 methods in my js GameAPI for working with background streaming music:
(function(scope) {
'use strict';
var sounds = {};
var STOP_DURATION = 1000;
var PAUSE_DURATION = 500;
scope.GameAPI = {
// create, load and play new music or unpause existing sound
playMusic: function(url, volume) {
var sound;
if (sounds[url]) {
sound = sounds[url];
sound.fade(0, volume, PAUSE_DURATION);
} else {
sound = new Howl({
src: [url],
html5: true,
loop: true
});
sound.fade(0, volume, STOP_DURATION);
sounds[url] = sound;
}
sound.play();
},
// pause current track
pauseMusic: function(url) {
if (!sounds[url]) {
return;
}
var sound = sounds[url];
sound.once('fade', function() {
sound.pause();
});
sound.fade(sound.volume(), 0, PAUSE_DURATION);
},
// fade, stop and dispose existing music
stopMusic: function(url) {
if (!sounds[url]) {
return;
}
var sound = sounds[url];
sound.once('fade', function() {
sound.stop();
});
sound.fade(sound.volume(), 0, STOP_DURATION);
delete sounds[url];
}
};
}(this));
1 Like