6

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

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

4

1 回答 1

10

我直接想到的两种方式:

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>

于 2018-09-11T08:59:28.433 回答