1- import { Component } from 'preact' ;
1+ import { useEffect , useState } from 'preact/hooks ' ;
22import { AudioVisualiser } from './audio-visualiser' ;
33
44export interface AudioAnalyserProps {
@@ -7,55 +7,41 @@ export interface AudioAnalyserProps {
77 width ?: number ;
88 height ?: number ;
99}
10-
11- export interface AudioAnalyserState {
12- audioData : Uint8Array ;
13- }
14-
15- export class AudioAnalyser extends Component < AudioAnalyserProps , AudioAnalyserState > {
16- public audioContext ?: AudioContext ;
17- public analyser ?: AnalyserNode ;
18- public dataArray ?: Uint8Array ;
19- public source ?: MediaStreamAudioSourceNode ;
20- public rafId ?: number ;
21-
22- constructor ( props : AudioAnalyserProps ) {
23- super ( props ) ;
24-
25- this . state = { audioData : new Uint8Array ( 0 ) } ;
26-
27- this . tick = this . tick . bind ( this ) ;
28- }
29-
30- componentDidMount ( ) {
31- this . audioContext = new AudioContext ( ) ;
32- this . analyser = this . audioContext . createAnalyser ( ) ;
33- this . dataArray = new Uint8Array ( this . analyser . frequencyBinCount ) ;
34- this . source = this . audioContext . createMediaStreamSource ( this . props . audio ) ;
35- this . source . connect ( this . analyser ) ;
36- this . rafId = requestAnimationFrame ( this . tick ) ;
37- }
38-
39- tick ( ) {
40- this . analyser ! . getByteTimeDomainData ( this . dataArray ! ) ;
41- this . setState ( { audioData : this . dataArray } ) ;
42- this . rafId = requestAnimationFrame ( this . tick ) ;
43- }
44-
45- componentWillUnmount ( ) {
46- cancelAnimationFrame ( this . rafId ! ) ;
47- this . analyser ! . disconnect ( ) ;
48- this . source ! . disconnect ( ) ;
49- }
50-
51- render ( ) {
52- return (
53- < AudioVisualiser
54- width = { this . props . width }
55- height = { this . props . height }
56- classes = { this . props . classses }
57- audioData = { this . state . audioData }
58- />
59- ) ;
60- }
10+ export function AudioAnalysera ( {
11+ width,
12+ height,
13+ classses,
14+ audio,
15+ } : AudioAnalyserProps ) {
16+ const [ audioData , setAudioData ] = useState ( new Uint8Array ( 0 ) ) ;
17+
18+ useEffect ( ( ) => {
19+ const audioContext = new AudioContext ( ) ;
20+ const analyser = audioContext . createAnalyser ( ) ;
21+ const dataArray = new Uint8Array ( analyser . frequencyBinCount ) ;
22+ const source = audioContext . createMediaStreamSource ( audio ) ;
23+
24+ source . connect ( analyser ) ;
25+
26+ let rafID = requestAnimationFrame ( function tick ( ) {
27+ analyser . getByteTimeDomainData ( dataArray ) ;
28+ setAudioData ( dataArray ) ;
29+ rafID = requestAnimationFrame ( tick ) ;
30+ } ) ;
31+
32+ return ( ) => {
33+ cancelAnimationFrame ( rafID ) ;
34+ analyser . disconnect ( ) ;
35+ source . disconnect ( ) ;
36+ } ;
37+ } , [ audioData ] ) ;
38+
39+ return (
40+ < AudioVisualiser
41+ width = { width }
42+ height = { height }
43+ classes = { classses }
44+ audioData = { audioData }
45+ />
46+ ) ;
6147}
0 commit comments