Skip to content

Instantly share code, notes, and snippets.

@chrisallick
Created December 7, 2016 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisallick/28da26a4971f20a38b913eedac3d722e to your computer and use it in GitHub Desktop.
Save chrisallick/28da26a4971f20a38b913eedac3d722e to your computer and use it in GitHub Desktop.
preload, play, and crossfade audio tracks in p5js
var audio = [];
var numTracks = 4;
function preload() {
audio[0] = loadSound('/audio/001.mp3');
audio[1] = loadSound('/audio/002.mp3');
audio[2] = loadSound('/audio/003.mp3');
audio[3] = loadSound('/audio/004.mp3');
}
function setup() {
createCanvas( windowWidth, windowHeight );
noLoop();
}
function draw() {}
function fadeTrack(tid, time) {
console.log("fading: " + tid);
audio[tid].setVolume(0, time);
setTimeout(function() {
audio[tid].stop();
}, (time*1000)+250);
}
function playTrack(tid, volume, time) {
console.log("playing: " + tid);
if( !audio[tid].isPlaying() ) {
audio[tid].play();
audio[tid].setVolume(0);
setTimeout(function(){
audio[tid].setVolume(volume, time);
}, 100);
}
}
function keyPressed() {
var key = keyCode - 49;
if( key >= 0 && key < numTracks ) {
console.log( "key pressed: " + key );
for( var i = 0; i < numTracks; i++ ) {
if( i != key ) {
if( audio[i].isPlaying() ) {
fadeTrack( i, 2 );
}
}
}
if( !audio[key].isPlaying() ) {
playTrack( key, .3, 5 );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment