如何使用JavaScript从上传的音频文件或音频文件URL创建MediaStream?

时间:2018-09-10 18:24:46

标签: javascript mediastream

我知道如何使用navigator.getUserMedia从浏览器和系统的默认输入设备(麦克风)获取音频流。但是,如果我想从上传的音频文件或音频文件URL中获取MediaStream,该怎么办?

赞赏是否可以提供代码示例。

1 个答案:

答案 0 :(得分:1)

直接想到两种方法:

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>