forked from alex2wong/vudio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wave.html
92 lines (73 loc) · 3.13 KB
/
wave.html
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
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas id="oscilloscope" style="width:100%;height:100%"></canvas>
<audio id="audio" autoplay src="demo_src/nuanchun.mp3"></audio>
<script>
var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
var audioElement = document.querySelector('audio');
var analyser = audioCtx.createAnalyser();
var sourceNode = audioCtx.createMediaElementSource(audioElement);
sourceNode.connect(analyser);
analyser.connect(audioCtx.destination);
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
var amplitude = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
// Get a canvas defined with ID "oscilloscope"
var canvas = document.getElementById("oscilloscope");
var canvasCtx = canvas.getContext("2d");
var time = 0.0;
var offset = 0;
// draw an oscilloscope of the current audio source
function draw() {
var curTime = audioCtx.currentTime.toFixed(1);
var amplitudeCur = 0;
requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
analyser.getByteFrequencyData(amplitude);
canvasCtx.fillStyle = "#fac122";
canvasCtx.fillRect(0, canvas.height*.2, canvas.width, canvas.height*.8);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = "#fff";
canvasCtx.beginPath();
var sliceWidth = canvas.width * 1.0 / bufferLength;
var x = 0;
for (var i = 0; i < bufferLength; i++) {
var v = dataArray[i] / 256.0;
var y = v * canvas.height / 2 + 80;
if (i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();
if ((curTime - time) <= .01) {
if (time > canvas.width && time % canvas.width <= 0.1) {
console.warn(time % canvas.width);
canvasCtx.fillStyle = "#fff";
canvasCtx.fillRect(0, 0, canvas.width, canvas.height*.2);
offset += canvas.width;
}
time += .1;
amplitudeCur = amplitude.reduce(function(pre, cur) { return pre + cur; }, 0)/bufferLength;
canvasCtx.fillStyle = "#fac122";
canvasCtx.beginPath();
var marginTop = canvas.height *.2* (1-(amplitudeCur/128));
canvasCtx.fillRect((time - offset) * 1, marginTop, 1, canvas.height *.2* - marginTop);
canvasCtx.fill();
}
}
draw();
</script>
</body>
</html>