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.
You can obtain a MediaStream object either by using the constructor or by calling functions such as MediaDevices. getUserMedia() , MediaDevices. getDisplayMedia() , or HTMLCanvasElement. captureStream() .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With