Created
December 7, 2016 18:06
-
-
Save chrisallick/28da26a4971f20a38b913eedac3d722e to your computer and use it in GitHub Desktop.
preload, play, and crossfade audio tracks in p5js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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