前言

来自于 Web Audio Api

音频可视化

话不多说直接上代码。最终显示的图是频谱图。

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
class Index extends React.Component<any, any> {
ref: HTMLAudioElement
canvas: HTMLCanvasElement
ctx: CanvasRenderingContext2D
uint8Arr: Uint8Array
start () {
this.ref.play()
const audioCtx = new AudioContext()
const audio = document.getElementById('audio') as HTMLMediaElement
const src = audioCtx.createMediaElementSource(audio)
const gainNode = audioCtx.createGain()
src.connect(gainNode)
const analyserNode = audioCtx.createAnalyser()
gainNode.connect(analyserNode)
const processingNode = audioCtx.createScriptProcessor(1024)
this.uint8Arr = new Uint8Array(analyserNode.frequencyBinCount)
const canvas = document.getElementById('canvas') as HTMLCanvasElement
const ctx = canvas.getContext('2d')
this.canvas = canvas
this.ctx = ctx
ctx.fillStyle = 'red'
processingNode.onaudioprocess = e => {
analyserNode.getByteFrequencyData(this.uint8Arr)
// 以下代码用于 给音频添加白噪音
// const inputBuf = e.inputBuffer
// const outputBuf = e.outputBuffer
// for (let outChannel = 0; outChannel < outputBuf.numberOfChannels; outChannel ++) {
// const inputDate = inputBuf.getChannelData(outChannel)
// const outputData = outputBuf.getChannelData(outChannel)
// for (let i = 0; i < inputBuf.length; i ++) {
// outputData[i] = inputDate[i]
// outputData[i] += ((Math.random() * 2) - 1) * 0.2
// }
// }
}
processingNode.connect(gainNode)
gainNode.connect(audioCtx.destination)
}
draw () {
const inner = () => {
const {ctx, canvas, uint8Arr} = this
ctx.clearRect(0, 0, canvas.width, canvas.height)
uint8Arr.forEach((item, i) => {
const height = item
const x = 2.5 * i
ctx.fillRect(x, canvas.height - height, 2, height)
})
requestAnimationFrame(inner)
}
return inner()
}
handleStart () {
this.start()
this.draw()
}
render () {
return (
<div className="main">
<div>
<button onClick={() => this.handleStart()}>start</button>
</div>
<canvas id="canvas" width="2560" height="300"></canvas>
<audio
ref={ref => this.ref = ref}
src="http://127.0.0.1:7070/music.mp3"
id="audio"
crossOrigin="anonymous"
></audio>
</div>
)
}
}