mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-07-22 23:23:55 +08:00
refactor(音频处理): 提取音频上下文创建逻辑到独立函数
将重复的音频上下文创建逻辑提取到独立的getAudioContextInstance函数中,减少代码重复并统一音频上下文配置
This commit is contained in:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user