mozAV2AudioOnly

Muaz Khan edited this page May 6, 2018 · 2 revisions

This wiki explains how to extract audio-only stream from Audio/Video MediaStream object using Firefox.

// mozAV2AudioOnly.js
// this script takes MediaStream with both audio/video tracks
// and returns only audio stream
// keep "audioContext" global to make sure "destination" isn't auto disconnected.
var audioContext, microphone, audioDestination;

navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true
}).then(function(avStream) {
    audioContext = new AudioContext();

    // simply connect with audio (live) APM source
    microphone = audioContext.createMediaStreamSource(avStream);

    // simply create destination node
    audioDestination = audioContext.createMediaStreamDestination();
    microphone.connect(audioDestination);

    // preview in DOM
    var audio = document.createElement('audio');
    audio.src = URL.createObjectURL(audioDestination.stream);
    audio.controls = true;
    audio.play();
    document.body.appendChild(audio);
}).catch(function(error) {});

Construct New MediaStream

var audioOnlyStream = new MediaStream();

cameraStream.getAudioTracks().forEach(function(audioTrack) {
    audioOnlyStream.addTrack(audioTrack);
});

var recorder = new MediaRecorder(audioOnlyStream);

removeTrack (video track)

cameraStream.getVideoTracks().forEach(function(videoTrack) {
    cameraStream.addTrack(videoTrack);
});

// now cameraStream has no video tracks
// it has only audio tracks
var recorder = new MediaRecorder(cameraStream);
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.