【发布时间】:2021-05-12 18:37:20
【问题描述】:
我想使用 WebRTC 将音频从网页流式传输到本地服务器。该服务器将处理该音频并将其立即输出给用户。我需要实时。
我的代码实际上正在运行。但是我用 getUserMedia 向用户询问麦克风,我不需要那个麦克风。这很烦人。我可以做些什么来流式传输音频而无需向用户询问麦克风?
谢谢。
这是一个最小的工作示例(它深受https://github.com/aiortc/aiortc/blob/main/examples/server/client.js 的启发)。只有 cmets 的最后一部分很有趣:
let webSocket = new WebSocket('wss://0.0.0.0:8080/ws');
const config = { sdpSemantics: 'unified-plan' }
const pc = new RTCPeerConnection(config);
webSocket.onmessage = (message) => {
const data = JSON.parse(message.data);
switch(data.type) {
case "answer":
pc.setRemoteDescription(data.answer)
break;
default:
break;
}
};
function negotiate() {
return pc.createOffer()
.then(function(offer) {
return pc.setLocalDescription(offer);
})
.then(function() {
return new Promise(function(resolve) {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange', checkState);
resolve();
}
}
pc.addEventListener('icegatheringstatechange', checkState);
}
});
})
.then(function() {
const offer = pc.localDescription;
webSocket.send(
JSON.stringify({
type: "offer",
offer: {
sdp: offer.sdp,
type: offer.type
}
})
);
})
}
// Preparing the oscillator
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioCtx.createOscillator();
const serverDestination = audioCtx.createMediaStreamDestination();
oscillator.connect(serverDestination);
// Asking for useless microphone
navigator.mediaDevices.getUserMedia({audio: true})
.then(() => {
return negotiate();
});
// Actual streaming
const stream = new MediaStream();
serverDestination.stream.getTracks().forEach((track) => {
pc.addTrack(track, stream);
})
// User pushes button to start the oscillator
function play() {
oscillator.start();
};
【问题讨论】:
-
这可能是aiortc和mDNS的问题:github.com/feross/simple-peer/issues/502#issuecomment-511221792 aiortc直到几天前我第一次下载它之后才支持mDNS。但是我已经更新了它,它仍然无法正常工作。也许它仍然是错误的。我最终会考虑尝试使用其他后端。
-
据aiortc开发者称,目前火狐存在一个bug:github.com/aiortc/aiortc/issues/481
标签: webrtc audio-streaming web-audio-api