Refactor ASR plugin options and improve audio processing

- Renamed `hideTimeout` to `autoHideTimeout` for clarity.
- Updated the default options destructuring for better readability.
- Removed unnecessary comments and cleaned up the audio processing logic.
- Ensured that the audio buffer is processed correctly before sending to the `onAudioChunk` callback.
This commit is contained in:
Harvey Zack committed 2025-05-23 10:08:20 +08:00
1 parent 1ece90c582
commit 3f0a1bd433
12 files changed
+41 -45

No files matched your search

+11 -11
View File
@@ -1,7 +1,13 @@
import style from 'bundle-text:./style.less';
export default function artplayerPluginAsr(option = {}) {
const { hideTimeout = 10000, length = 3, interval = 100, sampleRate = 16000, onAudioChunk = () => null } = option;
const {
length = 3,
interval = 100,
sampleRate = 16000,
autoHideTimeout = 10000,
onAudioChunk = () => null,
} = option;
return (art) => {
let started = false;
@@ -39,7 +45,7 @@ export default function artplayerPluginAsr(option = {}) {
function append(subtitle) {
if (typeof subtitle !== 'string') return;
clearTimeout(hideTimer);
hideTimer = setTimeout(hide, hideTimeout);
hideTimer = setTimeout(hide, autoHideTimeout);
$asr.style.display = '';
$asr.innerHTML = splitByPunctuation(subtitle)
.map((line) => `<div class="art-asr-line">${line}</div>`)
@@ -134,21 +140,15 @@ export default function artplayerPluginAsr(option = {}) {
workletLoaded = true;
}
// 创建输出音频的 GainNode(正常播放)
gainNode = audioCtx.createGain();
gainNode.gain.value = 1;
recorderNode = new AudioWorkletNode(audioCtx, 'recorder-processor');
recorderNode.port.onmessage = (event) => {
bufferChunks.push(new Float32Array(event.data));
};
// 分流:识别和播放
audioSource.connect(recorderNode);
audioSource.connect(gainNode);
gainNode.connect(audioCtx.destination); // 正常声音输出
// recorderNode 不连接 destination,避免输出干扰
gainNode.connect(audioCtx.destination);
const CHUNK_SAMPLES = sampleRate * (interval / 1000);
timer = setInterval(async () => {
@@ -166,8 +166,8 @@ export default function artplayerPluginAsr(option = {}) {
if (accumulated.length < CHUNK_SAMPLES) return;
const chunkToSend = accumulated.slice(0, CHUNK_SAMPLES);
const pcm = floatTo16BitPCM(chunkToSend);
const subtitle = await onAudioChunk(pcm);
const buffer = floatTo16BitPCM(chunkToSend);
const subtitle = await onAudioChunk(buffer);
append(subtitle);
}, interval);