Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a MediaStream from a uploaded audio file or a audio file URL using javascript?

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.

like image 207
Peiti Li Avatar asked Sep 10 '18 18:09

Peiti Li


People also ask

How do I get MediaStream?

You can obtain a MediaStream object either by using the constructor or by calling functions such as MediaDevices. getUserMedia() , MediaDevices. getDisplayMedia() , or HTMLCanvasElement. captureStream() .

How do I stream from video element?

A stream is captured from the video element on the left using its captureStream() method and set as the srcObject of the video element on the right. The stream variable are in global scope, so you can inspect them from the browser console.


1 Answers

Two ways that come to my mind directly:

  • three liner with MediaElement.captureStream():
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>
  • a bit more with AudioContext.createMediaStreamDestination() and AudioContext.createMediaElementSource():
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>
like image 86
Kaiido Avatar answered Oct 02 '22 13:10

Kaiido