Skip to content

Instantly share code, notes, and snippets.

@fpauser
Created May 31, 2016 08:43
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 fpauser/e8b20190f33f6cd92986d943500923ec to your computer and use it in GitHub Desktop.
Save fpauser/e8b20190f33f6cd92986d943500923ec to your computer and use it in GitHub Desktop.
/* es6-yfied https://github.com/jakesgordon/javascript-audio-fx */
export default class AudioFX {
constructor(src, options = {}, onload = () => {}) {
this.detectCapabilities();
let formats = options.formats || [];
let format = this.choose(formats);
this.pool = [];
src = src + (format ? '.' + format : '');
if (this.hasAudio) {
for (let n = 0 ; n < (options.pool || 1) ; n++) {
let audio = this.create(src, options, n === 0 ? onload : null);
this.pool.push(audio);
}
} else {
onload();
}
this.audio = (this.pool.length === 1) ? this.pool[0] : this.pool;
}
play() {
let audio = this.find(this.pool);
if (audio) { audio.play(); }
}
stop() {
for (let n = 0 ; n < this.pool.length ; n++) {
let audio = this.pool[n];
audio.pause();
audio.currentTime = 0;
}
}
choose(formats) {
for (let n = 0 ; n < formats.length ; n++) {
if (this.hasAudio && this.hasAudio[formats[n]]) {
return formats[n];
}
}
}
find(audios) {
for (let n = 0 ; n < audios.length ; n++) {
let audio = audios[n];
if (audio.paused || audio.ended) {
return audio;
}
}
}
audioSupported(audio, type) {
let s = audio.canPlayType(type);
return (s === 'probably') || (s === 'maybe');
}
detectCapabilities() {
let audio = document.createElement('audio');
if (audio && audio.canPlayType) {
this.hasAudio = {
ogg: this.audioSupported(audio, 'audio/ogg; codecs="vorbis"'),
mp3: this.audioSupported(audio, 'audio/mpeg;'),
m4a: this.audioSupported(audio, 'audio/x-m4a;') || this.audioSupported(audio, 'audio/aac;'),
wav: this.audioSupported(audio, 'audio/wav; codecs="1"'),
loop: (typeof audio.loop === 'boolean') // some browsers (FF) dont support loop yet
};
} else {
this.hasAudio = false;
}
}
create(src, options, onload) {
let audio = document.createElement('audio');
if (onload) {
let ready = function() {
audio.removeEventListener('canplay', ready, false);
onload();
};
audio.addEventListener('canplay', ready, false);
}
if (options.loop && !this.hasAudio.loop) {
audio.addEventListener('ended', function() {
audio.currentTime = 0; audio.play();
}, false);
}
audio.volume = options.volume || 0.1;
audio.autoplay = options.autoplay;
audio.loop = options.loop;
audio.src = src;
return audio;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment