MediaRecorder:从多个麦克风录制

时间:2017-11-01 16:22:57

标签: javascript audio

我目前正在使用MediaRecorder API在应用程序中录制音频。

有没有办法从多个输入设备录制,比如两个麦克风?

我可以使用mediaDevices.enumerateDevices()获取设备列表,如here所示。

理想情况下,如果可能,我想选择两个或更多要记录的设备。

这可能吗?

2 个答案:

答案 0 :(得分:4)

解决方法是请求多个getUserMedia并将流与AudioContext混合。

以下是如何做到的。

const VIDEO_ID = 'video_id';
const MIC_1_ID = 'mic_1_id';
const MIC_2_ID = 'mic_2_id';

// Request permission
navigator.mediaDevices.getUserMedia({video: true, audio: true}).then(() => {

    // Loop over all available video and audio devices (input and output)
    navigator.mediaDevices.enumerateDevices().then(devices => {

        // Request exact devices
        const requests = [
            navigator.mediaDevices.getUserMedia({video: {deviceId: {exact: VIDEO_ID}}}),
            navigator.mediaDevices.getUserMedia({video: false, audio: {deviceId: {exact: MIC_1_ID}}}),
            navigator.mediaDevices.getUserMedia({video: false, audio: {deviceId: {exact: MIC_2_ID}}})
        ];

        // Wait for all device requests to resolve.
        Promise.all(requests).then(streams => {
            const ctx = new AudioContext();
            const dest = ctx.createMediaStreamDestination();

            // Connect streams to the destination audio stream.
            streams.map(stream => {
                ctx.createMediaStreamSource(stream).connect(dest);
            });

            const videoTrack = streams[0].getTracks()[0];
            const mixedTracks = dest.stream.getTracks()[0];

            // Combine video and audio tracks into single stream.
            const stream = new MediaStream([videoTrack, mixedTracks]);

            // Start recorder
            const recorder = new MediaRecorder(this.stream, this.settings.recorder);

            // ...
        });

    });
});

答案 1 :(得分:4)

此功能会将您的曲目合并为一个:

function mix(audioContext, streams) {
  const dest = audioContext.createMediaStreamDestination();
  streams.forEach(stream => {
    const source = audioContext.createMediaStreamSource(stream);
    source.connect(dest);
  });
  return dest.stream.getTracks()[0];
}