【发布时间】:2021-10-09 10:30:09
【问题描述】:
我正在尝试使用MediaStreamAudioDestinationNode 创建一个 1ch(单声道)MediaStreamTrack。按照标准,这应该是可以的。
const ctx = new AudioContext();
const destinationNode = new MediaStreamAudioDestinationNode(ctx, {
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
await ctx.resume(); // doesn't make a difference
// this fails
expect(destinationNode.stream.getAudioTracks()[0].getSettings().channelCount).equal(1);
结果:
- Chrome 92.0.4515.107 始终创建立体声轨道
- Firefox 90 不会为
destinationNode.stream.getAudioTracks()[0].getSettings()返回任何内容,即使应该完全支持getSettings()
我在这里做错了什么?
编辑: 显然,firefox 和 chrome 实际上都产生了单声道,他们只是没有告诉你真相。这是 Typescript 的解决方案:
async function getNumChannelsInTrack(track: MediaStreamTrack): Promise<number> {
// unfortunately, we can't use track.getSettings().channelCount, because
// - Firefox 90 returns {} from getSettings() => see: https://bugzilla.mozilla.org/show_bug.cgi?id=1307808
// - Chrome 92 always reports 2 channels, even if that's incorrect => see: https://bugs.chromium.org/p/chromium/issues/detail?id=1044645
// Workaround: Record audio and look at the recorded buffer to determine the number of audio channels in the buffer.
const stream = new MediaStream();
stream.addTrack(track);
const mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
return new Promise<number>((resolve) => {
setTimeout(() => {
mediaRecorder.stop();
mediaRecorder.ondataavailable = async ({ data }) => {
const offlineAudioContext = new OfflineAudioContext({
length: 1,
sampleRate: 48000,
});
const audioBuffer = await offlineAudioContext.decodeAudioData(
await data.arrayBuffer()
);
resolve(audioBuffer.numberOfChannels);
};
}, 1000);
});
}
【问题讨论】:
标签: javascript google-chrome firefox web-audio-api