簡體   English   中英

Javascript:是否<audio> .captureStream() 在沒有 play() 的情況下工作嗎?

[英]Javascript: Does <audio>.captureStream() work without play()?

在瀏覽器中,我想捕獲以 .mp3 作為源的音頻標簽的流,然后通過 WebRTC 將其實時發送到服務器。 我不想通過揚聲器聽到它。

是否可以在沒有揚聲器輸出的情況下調用 audioElement.play()?

new Audio()返回一個連接到瀏覽器默認音頻輸出設備的HTMLAudioElement 您可以通過運行在開發控制台中驗證這一點:

> new Audio().sinkId
<- ""

其中空字符串輸出指定用戶代理默認sinkId

HTMLAudioElement實例的輸出連接到非默認接收器的一種靈活方法(例如,如果您不想通過揚聲器聽到它而只想將其發送到另一個目的地,如WebRTC 對等連接),是使用全局AudioContext對象創建一個新的MediaStreamAudioDestinationNode 然后,您可以通過audioContext.createMediaElementSource(mp3Audio)從保存您的 mp3 文件的Audio對象中獲取MediaElementAudioSourceNode ,並將其連接到您的新音頻目標節點。 然后,當您運行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()

似乎可以將音頻元素靜音並仍然捕獲流:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM