7

I know how to use navigator.getUserMedia to get the audio stream from the browser and system's default input device(a microphone). But what if I would like to get the MediaStream from an uploaded audio file or an audio file URL?

Appreciate if can provide a code example.

Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
Peiti Li
  • 4,634
  • 9
  • 40
  • 57

1 Answers1

12

Two ways that come to my mind directly:

const audio = new Audio(url);
const stream = audio.captureStream();
audio.play(); // stream now has input

// more than two lines actually in stacksnippets®
const audio = new Audio("https://upload.wikimedia.org/wikipedia/en/d/dc/Strawberry_Fields_Forever_(Beatles_song_-_sample).ogg");
audio.loop = true;
audio.crossOrigin = 'anonymous';
audio.play();

const stream = audio.captureStream ? 
  audio.captureStream() :
  audio.mozCaptureStream ?
    audio.mozCaptureStream() :
    null;
// feed our visible receiver with this stream
receiver.srcObject = stream;
console.log(stream.toString());
<audio id="receiver" controls></audio>
const audio = new Audio(url);
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const stream_dest = ctx.createMediaStreamDestination();
const source = ctx.createMediaElementSource(audio);
source.connect(stream_dest);

const stream = stream_dest.stream;
audio.play();

const audio = new Audio("https://upload.wikimedia.org/wikipedia/en/d/dc/Strawberry_Fields_Forever_(Beatles_song_-_sample).ogg");
audio.loop = true;
audio.crossOrigin = 'anonymous';
audio.play();

const ctx = new (window.AudioContext || window.webkitAudioContext)();
const stream_dest = ctx.createMediaStreamDestination();
const source = ctx.createMediaElementSource(audio);
source.connect(stream_dest);

const stream = stream_dest.stream;

// feed our visible receiver with this stream
receiver.srcObject = stream;
console.log(stream.toString());
<audio id="receiver" controls></audio>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • In the case of using the `play()` approach, you may need to attach a callback to the Promise returned by `play()`, because the stream may not be properly initialized until after the `play()` Promise resolves. Some older browser versions do not return a promise from `play()`, though. – Mike Clark Nov 11 '20 at 17:24