You need to enable JavaScript to run this app. JS中如何通过getUserMedia流为Azure Speech SDK创建适配Safari的PushStream
优惠活动
大模型
产品
解决方案
定价
更多

JS中如何通过getUserMedia流为Azure Speech SDK创建适配Safari的PushStream

Safari环境下Azure Speech SDK 复用getUserMedia双链路实现方案

原有SpeechSDK.AudioConfig.fromDefaultMicrophoneInput是SDK内部独占麦克风采集入口,无法将同一份音频流旁路给文件存储链路,因此必须基于createPushStream自建音频输入链路,全程不依赖MediaRecorder完成Safari环境适配。

核心实现逻辑

  • 仅调用一次getUserMedia获取全局共享的音频流,避免重复占用麦克风设备
  • 通过Web Audio API的节点架构对音频流做数据分叉,同一份PCM采样同时分发到两个消费端:
    • 第一路:将标准化PCM数据写入Azure Speech的PushStream,为SpeechRecognizer提供输入
    • 第二路:将同一份PCM数据本地缓存,采集停止后直接封装为WAV文件,无需依赖MediaRecorder
  • 全链路统一对齐Azure Speech要求的16kHz/16bit/单声道PCM格式,避免重采样导致的识别偏差

完整可运行代码示例

// 1. 初始化Azure Speech的PushStream,替代SDK默认的麦克风采集入口
const speechPushStream = SpeechSDK.audio.AudioInputStream.createPushStream({
  samplesPerSecond: 16000,
  bitsPerSample: 16,
  channelCount: 1
});
// 用PushStream初始化AudioConfig,再构建SpeechRecognizer
const audioConfig = SpeechSDK.AudioConfig.fromStreamInput(speechPushStream);
const speechConfig = SpeechSDK.SpeechConfig.fromSubscription("你的订阅密钥", "服务区域");
const recognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);

// 全局变量维护路由状态和存储缓存
let sharedStream;
let audioContext;
let mediaStreamSource;
let scriptProcessor;
const pcmDataChunks = [];

// 辅助工具:往DataView写入字符串,用于生成WAV头
function writeString(view, offset, str) {
  for (let i = 0; i < str.length; i++) {
    view.setUint8(offset + i, str.charCodeAt(i));
  }
}

// 2. 获取统一的共享麦克风流
async function getSharedMicrophoneStream() {
  sharedStream = await navigator.mediaDevices.getUserMedia({
    audio: {
      channelCount: 1,
      sampleRate: 16000,
      echoCancellation: true,
      noiseSuppression: true
    }
  });
}

// 3. 搭建音频路由,实现双链路分发
async function setupAudioRoute() {
  // 兼容Safari的Web Audio API前缀
  const AudioContext = window.AudioContext || window.webkitAudioContext;
  audioContext = new AudioContext({ sampleRate: 16000 });
  // 处理Safari的自动播放限制:在用户交互触发时恢复AudioContext状态
  if (audioContext.state === 'suspended') {
    await audioContext.resume();
  }
  mediaStreamSource = audioContext.createMediaStreamSource(sharedStream);
  // 用ScriptProcessor抓取音频采样,兼容全版本Safari
  scriptProcessor = audioContext.createScriptProcessor(4096, 1, 1);
  scriptProcessor.onaudioprocess = (event) => {
    const inputChannelData = event.inputBuffer.getChannelData(0);
    // 浮点PCM转16bit整数格式,对齐Azure PushStream的输入要求
    const int16PCM = new Int16Array(inputChannelData.length);
    for (let i = 0; i < inputChannelData.length; i++) {
      int16PCM[i] = inputChannelData[i] * 0x7FFF;
    }
    // 第一路:推给Azure Speech识别链路
    speechPushStream.write(int16PCM);
    // 第二路:缓存本地PCM数据用于生成文件
    pcmDataChunks.push(int16PCM);
  };
  // 连接节点形成处理链路,零增益节点避免麦克风采音直接外放产生啸叫
  mediaStreamSource.connect(scriptProcessor);
  const zeroGain = audioContext.createGain();
  zeroGain.gain.value = 0;
  scriptProcessor.connect(zeroGain);
  zeroGain.connect(audioContext.destination);
}

// 4. 采集停止后将缓存的PCM封装为WAV文件
function exportWavFile() {
  // 拼接所有缓存的PCM块
  const totalPCMLength = pcmDataChunks.reduce((sum, chunk) => sum + chunk.length, 0);
  const totalPCM = new Int16Array(totalPCMLength);
  let offset = 0;
  pcmDataChunks.forEach(chunk => {
    totalPCM.set(chunk, offset);
    offset += chunk.length;
  });
  // 生成标准WAV文件头
  const wavBuffer = new ArrayBuffer(44 + totalPCM.length * 2);
  const view = new DataView(wavBuffer);
  writeString(view, 0, 'RIFF');
  view.setUint32(4, 36 + totalPCM.length * 2, true);
  writeString(view, 8, 'WAVE');
  writeString(view, 12, 'fmt ');
  view.setUint32(16, 16, true);
  view.setUint16(20, 1, true);
  view.setUint16(22, 1, true);
  view.setUint32(24, 16000, true);
  view.setUint32(28, 16000 * 2, true);
  view.setUint32(32, 2, true);
  view.setUint16(34, 16, true);
  writeString(view, 36, 'data');
  view.setUint32(40, totalPCM.length * 2, true);
  // 写入PCM采样数据
  for (let i = 0; i < totalPCM.length; i++) {
    view.setInt16(44 + i * 2, totalPCM[i], true);
  }
  // 触发文件下载
  const wavBlob = new Blob([view], { type: 'audio/wav' });
  const downloadUrl = URL.createObjectURL(wavBlob);
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = `recording_${Date.now()}.wav`;
  link.click();
  URL.revokeObjectURL(downloadUrl);
}

// 5. 全流程停止逻辑:清理资源、结束识别、导出文件
async function stopAllProcess() {
  speechPushStream.close();
  await recognizer.stopContinuousRecognitionAsync();
  scriptProcessor.disconnect();
  mediaStreamSource.disconnect();
  await audioContext.close();
  sharedStream.getAudioTracks().forEach(track => track.stop());
  exportWavFile();
  pcmDataChunks.length = 0;
}

运行注意事项

  • 全链路无MediaRecorder依赖:所有音频处理环节基于Web Audio API完成,完全适配Safari的运行环境限制
  • 单次麦克风占用:整个流程仅触发一次getUserMedia权限申请,避免双进程占用音频设备导致的权限报错
  • Safari特有适配:主动处理了AudioContext的webkit前缀、挂起状态自动恢复、零增益防啸叫三个常见的兼容性问题
  • 格式统一:从采集到推送给Azure的全程固定为16kHz采样、16位深度、单声道的PCM格式,不需要额外的重采样处理

内容的提问来源于stack exchange,提问作者MadeInLagny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 17:54:04