Last active
October 12, 2022 14:28
-
-
Save chrisn/af3f08f3ba4918638cb575b7f6adc55f to your computer and use it in GitHub Desktop.
Peaks.js custom player example with Howler.js
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
const audioContext = new AudioContext(); | |
const audioUrl = '/example.mp3'; | |
// Load audio file into audio buffer | |
const response = await fetch(audioUrl); | |
const audioData = await response.arrayBuffer(); | |
const audioBuffer = await audioContext.decodeAudioData(audioData); | |
// Create Peaks.js custom player object, using Howler.js | |
const player = { | |
_howler: new Howl({ | |
src: [audioUrl] // TODO: To avoid fetching the audio twice, can we pass in an AudioBuffer? | |
}), | |
_eventEmitter: null, | |
_intervalID: null, | |
init: function(eventEmitter) { | |
this._eventEmitter = eventEmitter; | |
this._intervalID = setInterval(this._onTimer.bind(this), 250); | |
return Promise.resolve(); | |
}, | |
destroy: function() { | |
clearInterval(this._intervalID); | |
this._howler.stop(); | |
this._howler.unload(); | |
this._howler = null; | |
this._eventEmitter = null; | |
}, | |
play: function() { | |
if (this.isPlaying()) { | |
return; | |
} | |
this._howler.play(); | |
this._eventEmitter.emit('player.playing', this.getCurrentTime()); | |
}, | |
pause: function() { | |
this._howler.pause(); | |
this._eventEmitter.emit('player.pause', this.getCurrentTime()); | |
}, | |
isPlaying: function() { | |
return this._howler.playing(); | |
}, | |
seek: function(time) { | |
this._howler.seek(time); | |
this._eventEmitter.emit('player.seeked', this.getCurrentTime()); | |
this._eventEmitter.emit('player.timeupdate', this.getCurrentTime()); | |
}, | |
isSeeking: function() { | |
return false; | |
}, | |
getCurrentTime: function() { | |
return this._howler.seek(); | |
}, | |
getDuration: function() { | |
return this._howler.duration(); | |
}, | |
_onTimer: function() { | |
if (this.isPlaying()) { | |
return; | |
} | |
const time = this.getCurrentTime(); | |
this._eventEmitter.emit('player.timeupdate', time); | |
} | |
}; | |
var options = { | |
containers: { | |
zoomview: document.getElementById('zoomview-container'), | |
overview: document.getElementById('overview-container') | |
}, | |
player: player, | |
webAudio: { | |
audioBuffer: audioBuffer, | |
scale: 128, | |
multiChannel: false | |
}, | |
keyboard: true, | |
showPlayheadTime: true, | |
zoomLevels: [128, 256, 512, 1024, 2048, 4096] | |
}; | |
// Initialise Peaks.js instance | |
Peaks.init(options, function(err, peaksInstance) { | |
if (err) { | |
console.error(err.message); | |
return; | |
} | |
console.log('Peaks instance ready'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment