-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandomeow.js
88 lines (79 loc) · 2.13 KB
/
randomeow.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
87
88
var buffers = [];
var context;
var urls = ['cat1.mp3', 'cat2.mp3', 'cat3.mp3', 'cat4.mp3', 'cat5.mp3', 'cat6.mp3', 'cat7.mp3', 'cat8.mp3'];
function init() {
try {
window.AudioContext = window.AudioContext||window.webkitAudioContext;
context = new AudioContext();
}
catch(e) {
alert('Web Audio API is not supported in this browser');
}
loadSounds();
}
function loadSounds() {
for (i = 0; i < urls.length; ++i) {
loadSound(i);
}
}
function loadSound(index) {
var url = urls[index];
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
context.decodeAudioData(
request.response,
function (buffer) {
buffers[index] = buffer;
for (i = 0; i < urls.length; ++i) {
if (!(i in buffers)) {
return;
}
}
var button = document.getElementById('playSoundsButton');
button.disabled = false;
button.value = 'Listen';
},
alert);
}
request.send();
}
function playSound(which, when) {
var source = context.createBufferSource();
source.buffer = buffers[which];
source.connect(context.destination);
source.start(when);
}
function isInteger(s) {
for (i = 0; i < s.length; ++i) {
if (s[i] >= 0 && s[i] <= 9) {
continue;
} else {
return false;
}
}
return true;
}
function randomSounds() {
// The web audio API needs a user gesture before it can
// actually play something.
context.resume();
var startTime = context.currentTime + 1;
var howLong = document.getElementById('howLong').value;
if (!isInteger(howLong) || howLong < 1 || howLong > 60) {
alert('invalid number for step 1');
return;
}
var howOften = document.getElementById('howOften').value;
if (!isInteger(howOften) || howOften < 1 || howOften > 100) {
alert('invalid number for step 2');
return;
}
for (i = 0; i < howOften; ++i) {
var which = Math.floor(Math.random() * urls.length);
var when = Math.random() * howLong;
playSound(which, startTime + when);
}
}
window.addEventListener('load', init, false);