Impact

This forum is read only and just serves as an archive. If you have any questions, please post them on github.com/phoboslab/impact

1 decade ago by FelipeBudinich

I've been messing around with Audio lately, and I missed the ability to perform fade ins (as my music is looped, and it felt kind of akward to switch tracks), so I made an inject to ig.Music :

ig.Music.inject({
	
	_loop: true,
	
	crossFade: function( time, name ) {
		if( !this.currentTrack ) { return; }
		clearInterval( this._fadeInterval );
		this.fadeTimer = new ig.Timer( time );
		this.duration = time;
		this.nextTrack = name;
		this._fadeInterval = setInterval( this._crossfadeStep.bind(this), 50 );
	},
	
	_crossfadeStep: function() {
		var v = this.fadeTimer.delta()
			.map(-this.fadeTimer.target, 0, 1, 0)
			.limit( 0, 1 )
			* this._volume;
		if( v <= 0.01 ) {
			
			this.play(this.nextTrack);
			this.currentTrack.volume = this._volume;
			clearInterval( this._fadeInterval );
			this.fadeIn(this.duration);
		}
		else {
			this.currentTrack.volume = v;
		}
	},
	
	fadeIn: function ( time ) {
		if( !this.currentTrack ) { return; }
		this.currentTrack.volume = 0;
		clearInterval( this._fadeInterval );
		this.fadeTimer = new ig.Timer( time );
		this._fadeInterval = setInterval( this._fadeInStep.bind(this), 50 );
	},
	
	_fadeInStep: function() {
		var v = this.fadeTimer.delta()
			.map(this.fadeTimer.target, 0, 1, 0)
			.limit( 0, 1 )
			* this._volume;
		
		if( v == 1 ) {
			this.currentTrack.volume = this._volume;
			clearInterval( this._fadeInterval );
		}
		else {
			this.currentTrack.volume = v;
		}
	},

	});

Basically you call ig.music.crossFade( time, trackname), and it will go to the named track like this:

- Fade out the current track.
- Play the named track, while fading it in.

Cheers!

PS: Improvements welcome ;-D

1 decade ago by Hareesun

That's damn cool. Gonna try that out soon. Thanks!

1 decade ago by alexandre

Excellent injection. Will come in handy. Thanks!

1 decade ago by FelipeBudinich

Thanks for the kind words :-)

By the way, on my codebase I changed the name from crossFade() to fadeTo() as it is more accurate.
Page 1 of 1
« first « previous next › last »