All files / src/components VowelDetectButton.tsx

94.02% Statements 63/67
66.66% Branches 8/12
100% Functions 17/17
96.87% Lines 62/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                4x 4x 4x 1332x 1332x 1332x 1272x 1272x   1332x 1304x       2x                                                                   15x 5x     15x                       2x   3x   3x 5x     3x 3x 3x   3x 3x   3x 3x 3x 3x 3x 3x 3x       3x 3x 4x   4x   4x 4x 4x 1332x     4x 1332x 1332x 1332x 1332x   4x   3x 3x 2x     3x   3x       3x                 15x 5x 5x   15x                                           15x   15x 2x         15x 12x 12x 10x       15x                                    
import {Popover} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {Formant} from '../utils/pixiUtils/metaData/ImageMetaData';
import './vowelDetect.css';
import {SmileOutlined} from '@ant-design/icons';
import {isMobile} from '../utils/AgentCheck';
 
function getMonvingAverage(period: number) {
  const arr: number[] = [];
  let sum = 0;
  return (value: number) => {
    sum += value;
    arr.push(value);
    if (arr.length >= period) {
      sum -= arr[0];
      arr.shift();
    }
    if (arr.length < period / 2) return 0;
    return sum / arr.length;
  };
}
 
export const formants: Formant[] = [
  {
    label: 'A',
    array: [],
  },
  {
    label: 'I',
    array: [],
  },
  {
    label: 'U',
    array: [],
  },
  {
    label: 'E',
    array: [],
  },
  {
    label: 'O',
    array: [],
  },
];
 
interface VowelDetectButtonProps {
  stream: MediaStream;
}
 
interface VowelInputProps {
  vowel: string;
  setVowels: (arg0: number[]) => void;
  smad: number[];
}
 
function VowelInput(props: VowelInputProps) {
  const doneClick = () => {
    props.setVowels([...props.smad]);
  };
 
  return (
    <>
      <pre>
        {props.vowel + ' '}
        <button className="save-button" onClick={doneClick}>
          저장
        </button>
      </pre>
    </>
  );
}
 
const smad: number[] = [];
function VowelDetect(props: VowelDetectButtonProps): JSX.Element {
  const canvasRef = useRef<HTMLCanvasElement>(null);
 
  const saveVowelDataToBrowser = () => {
    localStorage.setItem('formants', JSON.stringify(formants));
  };
 
  useEffect(() => {
    Iif (!canvasRef.current) return;
    const ctx = canvasRef.current.getContext('2d');
 
    const canvas = canvasRef.current;
    Iif (!ctx) return;
 
    const audioContext = new AudioContext();
    const source = audioContext.createMediaStreamSource(props.stream);
    const analyser = audioContext.createAnalyser();
    source.connect(analyser);
    analyser.smoothingTimeConstant = 0.6;
    analyser.fftSize = 2048; //
    const byteFrequencyDataArray = new Uint8Array(
      analyser.frequencyBinCount / 3,
    );
 
    let aniNumber = 0;
    const callback = () => {
      ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
 
      analyser.getByteFrequencyData(byteFrequencyDataArray);
 
      const sma = getMonvingAverage(16);
      smad.length = 0;
      byteFrequencyDataArray.forEach(value => {
        smad.push(sma(value));
      });
 
      smad.forEach((value, idx) => {
        ctx.beginPath();
        ctx.moveTo(idx, canvas.clientHeight);
        ctx.lineTo(idx, canvas.clientHeight - value);
        ctx.stroke();
      });
      aniNumber = requestAnimationFrame(callback);
    };
    aniNumber = requestAnimationFrame(callback);
    return () => {
      cancelAnimationFrame(aniNumber);
    };
  }, [props.stream]);
  let canvasSize = '250px';
  // mobile 환경 캐치
  Iif (isMobile()) {
    canvasSize = '130px';
  }
 
  return (
    <div id="vowel-detect">
      <div className="vowel-explain">
        다음 모음을 발음하며 <br />
        저장 버튼을 누르세요.
      </div>
      <div className="vowel-button-and-detect">
        <div className="vowel-button-set">
          {formants.map((value, idx) => {
            const setVowels = (arg0: number[]) => {
              formants[idx].array = arg0;
              saveVowelDataToBrowser();
            };
            return (
              <VowelInput
                key={idx}
                vowel={value.label}
                setVowels={setVowels}
                smad={smad}
              ></VowelInput>
            );
          })}
        </div>
        <canvas
          width={canvasSize}
          height="160px"
          className="vowel-wave-canvas"
          ref={canvasRef}
        ></canvas>
      </div>
    </div>
  );
}
 
function VowelDetectButton(props: VowelDetectButtonProps): JSX.Element {
  const [visible, setVisible] = useState(false);
 
  const onESCKeyDown = (e: KeyboardEvent) => {
    Iif (e.key === 'Escape') {
      setVisible(false);
    }
  };
 
  useEffect(() => {
    window.addEventListener('keydown', onESCKeyDown);
    return () => {
      window.removeEventListener('keydown', onESCKeyDown);
    };
  }, []);
 
  return (
    <>
      <Popover
        placement={'topRight'}
        visible={visible}
        onVisibleChange={setVisible}
        trigger={['click']}
        content={<VowelDetect {...props}></VowelDetect>}
      >
        <a>
          <SmileOutlined className="navbar_button" />
        </a>
      </Popover>
    </>
  );
}
 
export default VowelDetectButton;