Merge pull request #2099 from Minamiyama/refactor/audio-context-singleton

refactor(音频处理): 提取音频上下文创建逻辑到独立函数
This commit is contained in:
hrz
2025-08-23 22:25:11 +08:00
committed by GitHub
+14 -22
View File
@@ -230,6 +230,16 @@
const conversationDiv = document.getElementById('conversation');
const logContainer = document.getElementById('logContainer');
function getAudioContextInstance() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: SAMPLE_RATE,
latencyHint: 'interactive'
});
log('创建音频上下文,采样率: ' + SAMPLE_RATE + 'Hz', 'debug');
}
return audioContext;
}
// 初始化可视化器
function initVisualizer() {
@@ -306,12 +316,7 @@
// 确保Opus解码器已初始化
try {
// 确保音频上下文存在
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: SAMPLE_RATE
});
log('创建音频上下文,采样率: ' + SAMPLE_RATE + 'Hz', 'debug');
}
audioContext = getAudioContextInstance();
// 确保解码器已初始化
if (!opusDecoder) {
@@ -617,10 +622,7 @@
log('已获取麦克风访问权限', 'success');
// 创建音频上下文
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: 16000, // 确保采样率与服务器期望的一致
latencyHint: 'interactive'
});
audioContext = getAudioContextInstance();
const source = audioContext.createMediaStreamSource(stream);
// 获取实际音频轨道设置
@@ -1416,12 +1418,7 @@
// 创建音频处理器
async function createAudioProcessor() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: 16000,
latencyHint: 'interactive'
});
}
audioContext = getAudioContextInstance();
try {
// 检查是否支持AudioWorklet
@@ -1616,12 +1613,7 @@
});
// 创建音频上下文和分析器
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: 16000,
latencyHint: 'interactive'
});
}
audioContext = getAudioContextInstance();
// 创建音频处理器
const processorResult = await createAudioProcessor();