来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
370 lines
12 KiB
TypeScript
370 lines
12 KiB
TypeScript
import { useCallback, useRef, useState } from 'react';
|
|
import { formatAiErrorMessage } from '../utils/arkErrors';
|
|
|
|
export type VoiceAudioReadyPayload = {
|
|
audioBase64: string;
|
|
audioFormat: string;
|
|
};
|
|
|
|
interface UseServerVoiceRecordingOptions {
|
|
onAudioReady?: (payload: VoiceAudioReadyPayload) => void | Promise<void>;
|
|
onError?: (message: string) => void;
|
|
}
|
|
|
|
function pickMimeType(): string {
|
|
const candidates = ['audio/ogg;codecs=opus', 'audio/webm;codecs=opus', 'audio/webm'];
|
|
return candidates.find((type) => MediaRecorder.isTypeSupported(type)) || '';
|
|
}
|
|
|
|
function mimeToFormat(mimeType: string): string {
|
|
if (mimeType.includes('ogg')) return 'ogg';
|
|
if (mimeType.includes('wav')) return 'wav';
|
|
if (mimeType.includes('mpeg') || mimeType.includes('mp3')) return 'mp3';
|
|
return 'webm';
|
|
}
|
|
|
|
function blobToBase64(blob: Blob): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
reader.onloadend = () => {
|
|
const result = reader.result as string;
|
|
resolve(result.includes(',') ? result.split(',')[1] : result);
|
|
};
|
|
reader.onerror = () => reject(new Error('音频读取失败'));
|
|
reader.readAsDataURL(blob);
|
|
});
|
|
}
|
|
|
|
function getAudioContextConstructor() {
|
|
if (typeof window === 'undefined') return null;
|
|
return window.AudioContext || (window as any).webkitAudioContext || null;
|
|
}
|
|
|
|
function encodeWav(pcm: Float32Array, sampleRate: number) {
|
|
const buffer = new ArrayBuffer(44 + pcm.length * 2);
|
|
const view = new DataView(buffer);
|
|
const writeString = (byteOffset: number, value: string) => {
|
|
for (let i = 0; i < value.length; i += 1) {
|
|
view.setUint8(byteOffset + i, value.charCodeAt(i));
|
|
}
|
|
};
|
|
|
|
writeString(0, 'RIFF');
|
|
view.setUint32(4, 36 + pcm.length * 2, true);
|
|
writeString(8, 'WAVE');
|
|
writeString(12, 'fmt ');
|
|
view.setUint32(16, 16, true);
|
|
view.setUint16(20, 1, true);
|
|
view.setUint16(22, 1, true);
|
|
view.setUint32(24, sampleRate, true);
|
|
view.setUint32(28, sampleRate * 2, true);
|
|
view.setUint16(32, 2, true);
|
|
view.setUint16(34, 16, true);
|
|
writeString(36, 'data');
|
|
view.setUint32(40, pcm.length * 2, true);
|
|
|
|
let byteOffset = 44;
|
|
for (let i = 0; i < pcm.length; i += 1) {
|
|
const sample = Math.max(-1, Math.min(1, pcm[i]));
|
|
view.setInt16(byteOffset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);
|
|
byteOffset += 2;
|
|
}
|
|
|
|
return new Blob([buffer], { type: 'audio/wav' });
|
|
}
|
|
|
|
function mergePcmChunks(chunks: Float32Array[]) {
|
|
const length = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
const pcm = new Float32Array(length);
|
|
let offset = 0;
|
|
for (const chunk of chunks) {
|
|
pcm.set(chunk, offset);
|
|
offset += chunk.length;
|
|
}
|
|
return pcm;
|
|
}
|
|
|
|
/**
|
|
* 按静音切段:口语停顿后拆成多段,转写时用换行分隔商品。
|
|
* 噪声过大时回退为整段。
|
|
*/
|
|
export function splitPcmBySilence(
|
|
chunks: Float32Array[],
|
|
sampleRate: number,
|
|
options?: { silenceMs?: number; silenceRms?: number; minSpeechMs?: number; maxSegments?: number }
|
|
): Float32Array[] {
|
|
const silenceMs = options?.silenceMs ?? 650;
|
|
const silenceRms = options?.silenceRms ?? 0.012;
|
|
const minSpeechMs = options?.minSpeechMs ?? 220;
|
|
const maxSegments = options?.maxSegments ?? 40;
|
|
const frameMs = 20;
|
|
const frameSize = Math.max(1, Math.floor((sampleRate * frameMs) / 1000));
|
|
const silenceFramesNeeded = Math.max(1, Math.round(silenceMs / frameMs));
|
|
const minSpeechFrames = Math.max(1, Math.round(minSpeechMs / frameMs));
|
|
|
|
const pcm = mergePcmChunks(chunks);
|
|
if (pcm.length < frameSize) {
|
|
return pcm.length ? [pcm] : [];
|
|
}
|
|
|
|
const segments: Float32Array[] = [];
|
|
let speechStart = -1;
|
|
let silenceRun = 0;
|
|
|
|
for (let i = 0; i + frameSize <= pcm.length; i += frameSize) {
|
|
let energy = 0;
|
|
for (let j = 0; j < frameSize; j += 1) {
|
|
const sample = pcm[i + j];
|
|
energy += sample * sample;
|
|
}
|
|
const rms = Math.sqrt(energy / frameSize);
|
|
const silent = rms < silenceRms;
|
|
|
|
if (!silent) {
|
|
if (speechStart < 0) speechStart = i;
|
|
silenceRun = 0;
|
|
continue;
|
|
}
|
|
|
|
if (speechStart < 0) continue;
|
|
silenceRun += 1;
|
|
if (silenceRun < silenceFramesNeeded) continue;
|
|
|
|
const speechEnd = i - (silenceRun - 1) * frameSize;
|
|
const frameCount = Math.floor((speechEnd - speechStart) / frameSize);
|
|
if (frameCount >= minSpeechFrames) {
|
|
segments.push(pcm.slice(speechStart, Math.max(speechStart + 1, speechEnd)));
|
|
if (segments.length >= maxSegments) {
|
|
const rest = pcm.slice(speechEnd);
|
|
if (rest.length >= frameSize) segments.push(rest);
|
|
return segments;
|
|
}
|
|
}
|
|
speechStart = -1;
|
|
silenceRun = 0;
|
|
}
|
|
|
|
if (speechStart >= 0) {
|
|
const frameCount = Math.floor((pcm.length - speechStart) / frameSize);
|
|
if (frameCount >= minSpeechFrames) {
|
|
segments.push(pcm.slice(speechStart));
|
|
}
|
|
}
|
|
|
|
return segments.length ? segments : [pcm];
|
|
}
|
|
|
|
function getUnsupportedMessage() {
|
|
if (typeof window === 'undefined') return '当前环境不支持录音';
|
|
if (!window.isSecureContext) {
|
|
return '当前页面不是安全连接,浏览器禁止访问麦克风。请使用 https://www.xdjchuanhui.com 打开系统';
|
|
}
|
|
if (!navigator.mediaDevices?.getUserMedia) {
|
|
return '当前浏览器不支持麦克风录音,请使用最新版 Chrome、Edge 或 Safari';
|
|
}
|
|
if (!getAudioContextConstructor() && typeof MediaRecorder === 'undefined') {
|
|
return '当前浏览器不支持录音编码,请使用最新版 Chrome、Edge 或 Safari';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function getMicrophoneErrorMessage(error: unknown) {
|
|
const name = error instanceof DOMException ? error.name : '';
|
|
switch (name) {
|
|
case 'NotAllowedError':
|
|
case 'SecurityError':
|
|
return '麦克风权限被拒绝。请点击浏览器地址栏左侧的权限图标,允许麦克风后刷新页面重试';
|
|
case 'NotFoundError':
|
|
case 'DevicesNotFoundError':
|
|
return '未检测到可用麦克风,请检查设备连接后重试';
|
|
case 'NotReadableError':
|
|
case 'TrackStartError':
|
|
return '麦克风正被其他程序占用,请关闭占用麦克风的软件后重试';
|
|
case 'OverconstrainedError':
|
|
case 'ConstraintNotSatisfiedError':
|
|
return '当前麦克风不支持所需录音参数,请更换设备或浏览器后重试';
|
|
case 'TypeError':
|
|
return getUnsupportedMessage() || '无法启动麦克风,请检查浏览器权限';
|
|
default:
|
|
return getUnsupportedMessage() || '无法访问麦克风,请在浏览器中允许麦克风权限';
|
|
}
|
|
}
|
|
|
|
export const useServerVoiceRecording = (options: UseServerVoiceRecordingOptions = {}) => {
|
|
const { onAudioReady, onError } = options;
|
|
const onAudioReadyRef = useRef(onAudioReady);
|
|
const onErrorRef = useRef(onError);
|
|
onAudioReadyRef.current = onAudioReady;
|
|
onErrorRef.current = onError;
|
|
|
|
const [isRecording, setIsRecording] = useState(false);
|
|
const [isTranscribing, setIsTranscribing] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [unsupportedMessage] = useState(getUnsupportedMessage);
|
|
const [isSupported] = useState(() => !getUnsupportedMessage());
|
|
|
|
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
|
|
const streamRef = useRef<MediaStream | null>(null);
|
|
const audioContextRef = useRef<AudioContext | null>(null);
|
|
const audioSourceRef = useRef<MediaStreamAudioSourceNode | null>(null);
|
|
const processorRef = useRef<ScriptProcessorNode | null>(null);
|
|
const wavChunksRef = useRef<Float32Array[]>([]);
|
|
const wavSampleRateRef = useRef(44100);
|
|
const chunksRef = useRef<Blob[]>([]);
|
|
const mimeTypeRef = useRef('');
|
|
|
|
const cleanupStream = useCallback(() => {
|
|
processorRef.current?.disconnect();
|
|
audioSourceRef.current?.disconnect();
|
|
void audioContextRef.current?.close().catch(() => undefined);
|
|
processorRef.current = null;
|
|
audioSourceRef.current = null;
|
|
audioContextRef.current = null;
|
|
streamRef.current?.getTracks().forEach((track) => track.stop());
|
|
streamRef.current = null;
|
|
mediaRecorderRef.current = null;
|
|
}, []);
|
|
|
|
const emitAudio = useCallback(async (blob: Blob, mimeType: string) => {
|
|
setIsTranscribing(true);
|
|
setError(null);
|
|
try {
|
|
const audioBase64 = await blobToBase64(blob);
|
|
if (!audioBase64) throw new Error('未录到音频,请重试');
|
|
await onAudioReadyRef.current?.({
|
|
audioBase64,
|
|
audioFormat: mimeToFormat(mimeType),
|
|
});
|
|
} catch (err) {
|
|
const message = formatAiErrorMessage(err instanceof Error ? err.message : '录音处理失败');
|
|
setError(message);
|
|
onErrorRef.current?.(message);
|
|
} finally {
|
|
setIsTranscribing(false);
|
|
}
|
|
}, []);
|
|
|
|
const startRecording = useCallback(async () => {
|
|
if (isRecording || isTranscribing) return;
|
|
if (!isSupported) {
|
|
const message = unsupportedMessage || '当前浏览器不支持录音';
|
|
setError(message);
|
|
onErrorRef.current?.(message);
|
|
return;
|
|
}
|
|
|
|
setError(null);
|
|
|
|
try {
|
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
audio: {
|
|
echoCancellation: true,
|
|
noiseSuppression: true,
|
|
autoGainControl: true,
|
|
},
|
|
});
|
|
streamRef.current = stream;
|
|
chunksRef.current = [];
|
|
wavChunksRef.current = [];
|
|
|
|
const AudioContextCtor = getAudioContextConstructor();
|
|
if (AudioContextCtor) {
|
|
const audioContext = new AudioContextCtor();
|
|
const source = audioContext.createMediaStreamSource(stream);
|
|
const processor = audioContext.createScriptProcessor(4096, 1, 1);
|
|
wavSampleRateRef.current = audioContext.sampleRate;
|
|
processor.onaudioprocess = (event) => {
|
|
const input = event.inputBuffer.getChannelData(0);
|
|
wavChunksRef.current.push(new Float32Array(input));
|
|
};
|
|
source.connect(processor);
|
|
processor.connect(audioContext.destination);
|
|
audioContextRef.current = audioContext;
|
|
audioSourceRef.current = source;
|
|
processorRef.current = processor;
|
|
setIsRecording(true);
|
|
return;
|
|
}
|
|
|
|
const mimeType = pickMimeType();
|
|
mimeTypeRef.current = mimeType;
|
|
const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
|
|
mediaRecorderRef.current = recorder;
|
|
|
|
recorder.ondataavailable = (event) => {
|
|
if (event.data.size > 0) {
|
|
chunksRef.current.push(event.data);
|
|
}
|
|
};
|
|
|
|
recorder.onstop = () => {
|
|
const blob = new Blob(chunksRef.current, {
|
|
type: mimeTypeRef.current || recorder.mimeType || 'audio/webm',
|
|
});
|
|
cleanupStream();
|
|
if (blob.size > 0) {
|
|
emitAudio(blob, blob.type).catch(() => undefined);
|
|
} else {
|
|
setError('未录到音频,请重试');
|
|
}
|
|
};
|
|
|
|
recorder.onerror = () => {
|
|
setError('录音失败,请重试');
|
|
cleanupStream();
|
|
setIsRecording(false);
|
|
};
|
|
|
|
recorder.start();
|
|
setIsRecording(true);
|
|
} catch (err) {
|
|
cleanupStream();
|
|
const message = getMicrophoneErrorMessage(err);
|
|
setError(message);
|
|
onErrorRef.current?.(message);
|
|
setIsRecording(false);
|
|
}
|
|
}, [cleanupStream, emitAudio, isRecording, isSupported, isTranscribing, unsupportedMessage]);
|
|
|
|
const stopRecording = useCallback(() => {
|
|
if (audioContextRef.current) {
|
|
setIsRecording(false);
|
|
const chunks = wavChunksRef.current;
|
|
const sampleRate = wavSampleRateRef.current;
|
|
cleanupStream();
|
|
if (chunks.length > 0) {
|
|
const blob = encodeWav(mergePcmChunks(chunks), sampleRate);
|
|
emitAudio(blob, 'audio/wav').catch(() => undefined);
|
|
} else {
|
|
setError('未录到音频,请重试');
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (!mediaRecorderRef.current || mediaRecorderRef.current.state === 'inactive') {
|
|
setIsRecording(false);
|
|
return;
|
|
}
|
|
setIsRecording(false);
|
|
try {
|
|
mediaRecorderRef.current.stop();
|
|
} catch {
|
|
cleanupStream();
|
|
}
|
|
}, [cleanupStream, emitAudio]);
|
|
|
|
const clearTranscript = useCallback(() => {
|
|
setError(null);
|
|
}, []);
|
|
|
|
return {
|
|
isRecording,
|
|
isTranscribing,
|
|
error,
|
|
isSupported,
|
|
startRecording,
|
|
stopRecording,
|
|
clearTranscript,
|
|
};
|
|
};
|