Skip to content

Commit

Permalink
fix audio input infinite rendering (#496)
Browse files Browse the repository at this point in the history
  • Loading branch information
newfish-cmyk authored Nov 20, 2023
1 parent b05dd0f commit 9c4eabf
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions projects/app/src/web/common/hooks/useSpeech.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { POST } from '../api/request';
import { useToast } from './useToast';
import { useTranslation } from 'next-i18next';
Expand All @@ -8,7 +8,8 @@ export const useSpeech = (props?: { shareId?: string }) => {
const { shareId } = props || {};
const { t } = useTranslation();
const mediaRecorder = useRef<MediaRecorder>();
const mediaStream = useRef<MediaStream>();
// const mediaStream = useRef<MediaStream>();
const [mediaStream, setMediaStream] = useState<MediaStream>();
const { toast } = useToast();
const [isSpeaking, setIsSpeaking] = useState(false);
const [isTransCription, setIsTransCription] = useState(false);
Expand All @@ -24,7 +25,7 @@ export const useSpeech = (props?: { shareId?: string }) => {
return `${formattedMinutes}:${formattedSeconds}`;
}, [audioSecond]);

const renderAudioGraph = (analyser: AnalyserNode, canvas: HTMLCanvasElement) => {
const renderAudioGraph = useCallback((analyser: AnalyserNode, canvas: HTMLCanvasElement) => {
const bufferLength = analyser.frequencyBinCount;
const backgroundColor = 'white';
const dataArray = new Uint8Array(bufferLength);
Expand All @@ -47,12 +48,12 @@ export const useSpeech = (props?: { shareId?: string }) => {
canvasCtx.fillRect(x, height - adjustedBarHeight, barWidth, adjustedBarHeight);
x += barWidth + 1;
}
};
}, []);

const startSpeak = async (onFinish: (text: string) => void) => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaStream.current = stream;
setMediaStream(stream);
mediaRecorder.current = new MediaRecorder(stream);
const chunks: Blob[] = [];
setIsSpeaking(true);
Expand Down Expand Up @@ -121,8 +122,8 @@ export const useSpeech = (props?: { shareId?: string }) => {
if (mediaRecorder.current && mediaRecorder.current.state !== 'inactive') {
mediaRecorder.current.stop();
}
if (mediaStream.current) {
mediaStream.current.getTracks().forEach((track) => track.stop());
if (mediaStream) {
mediaStream.getTracks().forEach((track) => track.stop());
}
};
}, []);
Expand All @@ -133,7 +134,7 @@ export const useSpeech = (props?: { shareId?: string }) => {
isSpeaking,
isTransCription,
renderAudioGraph,
stream: mediaStream.current,
stream: mediaStream,
speakingTimeString
};
};

0 comments on commit 9c4eabf

Please sign in to comment.