-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_audio_stream_fft.html
More file actions
83 lines (72 loc) · 2.7 KB
/
test_audio_stream_fft.html
File metadata and controls
83 lines (72 loc) · 2.7 KB
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
<!DOCTYPE html lang="en-US" html>
<head>
<title>
My Web API player
</title>
</head>
<body>
<button id="display_switch">Click for Sound</button>
<div id="my_audio_handler">
<audio
controls id="my_audio_player"
src="http://127.0.0.1:8088/static/one_last_kiss.flac" crossorigin="anonymous"></audio>
</div>
<div id="music_board">
<canvas
id="my_music_drawing" width="420" height="100"
style="border: solid;"
></canvas>
</div>
</body>
<script>
var buttonClicked = false
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var myAudio = document.querySelector('audio');
myAudio.crossOrigin = "anonymous";
var source = audioCtx.createMediaElementSource(myAudio);
var myAnalyzer = audioCtx.createAnalyser();
source.connect(myAnalyzer);
myAnalyzer.connect(audioCtx.destination);
myAnalyzer.fftSize = 4096;
var bufferLength = myAnalyzer.frequencyBinCount;
console.log(bufferLength)
var dataArray = new Uint8Array(bufferLength);
let canvas = document.getElementById("my_music_drawing")
let ctx = canvas.getContext("2d")
let WIDTH = canvas.width;
let HEIGHT = canvas.height;
let barWidth = (WIDTH / bufferLength) * 2.5
let barHeight
let x = 0
function renderFrame() {
requestAnimationFrame(renderFrame);
x = 0;
myAnalyzer.getByteFrequencyData(dataArray);
ctx.fillStyle = "white";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i] * 0.3;
let r = barHeight + (25 * (i/bufferLength));
let g = 250 * (i/bufferLength);
let b = 100;
ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
//x += barWidth + 1;
x += barWidth;
}
}
renderFrame()
document.querySelector('button').addEventListener('click', function() {
buttonClicked = !buttonClicked
if (buttonClicked) {
audioCtx.resume().then(() => {
console.log('Playback resumed successfully');
});
} else {
audioCtx.suspend().then(() => {
console.log('Playback stopnned successfully');
});
}
});
</script>
</html>