-
Notifications
You must be signed in to change notification settings - Fork 1
/
audio.js
86 lines (72 loc) · 2.39 KB
/
audio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var musicFiles = [];
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audio;
var audioSrc;
var analyser;
var bufferLength;
var dataArray; // frequency data
var audioBuffer;
var defaultMusic = true; //used to tell if we are currently running default music or not
function selectMusic(e) {
audio = null;
musicFiles = e.target.files;
var num = Math.floor(Math.random() * musicFiles.length);
var musicFile = URL.createObjectURL(musicFiles[num]);
$("#music").attr("src", musicFile);
defaultMusic = false;
}
function getFreq() {
requestAnimationFrame(getFreq);
analyser.getByteFrequencyData(dataArray);
}
function play() {
if((document.getElementById('music').paused && !defaultMusic && document.getElementById('autoplay').paused)){
document.getElementById('music').play();
if (!audio) {
audio = document.getElementById('music');
audio.crossOrigin = "anonymous";
audioSrc = audioCtx.createMediaElementSource(audio);
analyser = audioCtx.createAnalyser();
audioBuffer = audioCtx.createBufferSource();
analyser.fftSize = 256;
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);
bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
}
}
else if(audio && defaultMusic && document.getElementById('music').paused && document.getElementById('autoplay').paused){
document.getElementById('autoplay').play();
}
}
function stop() {
if(!defaultMusic)
document.getElementById('music').pause();
else
document.getElementById('autoplay').pause();
audio.currentTime = 0;
}
function pause(){
if(!defaultMusic)
document.getElementById('music').pause();
else
document.getElementById('autoplay').pause();
}
function playDefault(){
if(!audio){
audio = document.getElementById('autoplay');
audio.crossOrigin = "anonymous";
audioSrc = audioCtx.createMediaElementSource(document.getElementById('autoplay'));
analyser = audioCtx.createAnalyser();
audioBuffer = audioCtx.createBufferSource();
analyser.fftSize = 256;
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);
bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
defaultMusic = true;
}
}
window.onload = function (e) {
document.getElementById('music-files').addEventListener('change', selectMusic, false);
}