6

在浏览器中,我想捕获以 .mp3 作为源的音频标签的流,然后通过 WebRTC 将其实时发送到服务器。我不想通过扬声器听到它。

是否可以在没有扬声器输出的情况下调用 audioElement.play()?

4

2 回答 2

5

new Audio()返回HTMLAudioElement连接到浏览器默认音频输出设备的 。您可以通过运行在开发控制台中验证这一点:

> new Audio().sinkId
<- ""

其中空字符串输出指定用户代理默认值sinkId

将实例的输出连接HTMLAudioElement到非默认接收器的一种灵活方法(例如,如果您不想通过扬声器听到它,但只想将其发送到另一个目的地,如WebRTC 对等连接),是使用全局AudioContext对象创建一个新的MediaStreamAudioDestinationNode. 然后,您可以通过 获取保存 mp3 文件MediaElementAudioSourceNode的对象,并将其连接到新的音频目标节点。然后,当您运行时,它只会流式传输到目标节点,而不是默认(扬声器)音频输出。AudioaudioContext.createMediaElementSource(mp3Audio)mp3Audio.play()

完整示例:

// Set up the audio node source and destination...
const mp3FilePath = 'testAudioSample.mp3'
const mp3Audio = new Audio(mp3FilePath)
const audioContext = new AudioContext()
const mp3AudioSource = audioContext.createMediaElementSource(mp3Audio)
const mp3AudioDestination = audioContext.createMediaStreamDestination()
mp3AudioSource.connect(mp3AudioDestination)

// Connect the destination track to whatever you want,
// e.g. another audio node, or an RTCPeerConnection.
const mp3AudioTrack = mp3AudioDestination.stream.getAudioTracks()[0]
const pc = new RTCPeerConnection()
pc.addTrack(track)

// Prepare the `Audio` instance playback however you'd like.
// For example, loop it:
mp3Audio.loop = true

// Start streaming the mp3 audio to the new destination sink!
await mp3Audio.play()
于 2021-01-30T19:44:00.750 回答
2

似乎可以使音频元素静音并仍然捕获流:

audioElement.muted = true; var stream = audioElement.captureStream();

于 2018-10-02T20:46:24.343 回答