-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathscript.js
97 lines (74 loc) · 2.28 KB
/
script.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
89
90
91
92
93
94
95
96
97
// Browser support
window.AudioContext = window.AudioContext || window.webkitAudioContext;
// Initialize audio context
var context = new AudioContext();
// Destination
var destination = context.destination;
// Sound Url
var soundUrl = 'http://........';
// Buffer
var soundBuffer;
// Create request to load the song from address
var request = new XMLHttpRequest();
request.open('GET', soundUrl, true);
// Obtain as buffer array
request.responseType = 'arraybuffer';
// Send request and save it
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
soundBuffer = buffer;
});
};
request.send();
// Play sound
function play() {
// Create AudioBufferSource and attach buffer
var source = context.createBufferSource();
source.buffer = soundBuffer;
source.connect(context.destination);
// Play the source
source.start(0);
}
// Send request and save it
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
soundBuffer = buffer;
play();
});
};
<audio id="myAudioTag" controls>
<source src="music.ogg" type='audio/ogg; codecs=vorbis' />
</audio>
// Get the element from the DOM
var audioElement = document.getElementById('myAudioTag');
// Create a node based on the element
source = context.createMediaElementSource(audioElement);
source.connect(context.destination);
// Create oscillator and set up attributes
var oscillator = context.createOscillator();
oscillator.frequency.value = 261.63;
oscillator.type = 'square';
// Attach to destination
oscillator.connect(context.destination);
// Play oscillator
oscillator.start(0);
var frequencies = [261.63, 329.63, 392];
for (var i in frequencies) {
// Create oscillator and set up attributes
var oscillator = context.createOscillator();
oscillator.frequency.value = frequencies[i];
oscillator.type = 'square';
// Attach to destination
oscillator.connect(context.destination);
// Play oscillator
oscillator.start(0);
}
// Using one of the nodes of the previous examples
var webNode = getNodeFromPreviousExample();
// Create new GainNode
var gainNode = context.createGain();
// Attach webNode -&gt; gainNode -&gt; destination
webNode.connect(gainNode);
gainNode.connect(context.destination);
// Control the volume
gainNode.gain.value = 0.4;