如何将音频流传递到同一网站上的另一个页面



我想将音频源从网站/host流式传输到同一网站上的另一个页面/listen

这个原理似乎有点像在线广播、YouTube上的迷你播放器或Tidal或Spotify等流媒体服务,在那里你可以一边听音乐,一边切换到网站上的另一个页面,但听众永远不会访问/host。听众听到主持人在/host上说的话。一个简化的图形可能是这样的:

// ┌─────────────────────┐
// │                     │
// │  Host PC            │
// │                     │
// │  with microphone    │
// │                     │
// └───────────────┬─────┘
//                 │
// ┌───────────────▼─────┐
// │                     │
// │  Webserver          │
// │                     │
// └───────────────┬─────┘
//                 │
// ┌───────────────▼─────┐
// │                     │
// │  Admin panel page   │
// │                     │
// │  with input source  │ This page the host
// │                     │ is visiting.
// │  https://x.y/host   │
// │                     │
// └───────────────┬─────┘
//                 │
//                 │
// ┌───────────────▼─────┐
// │                     │ 
// │  User page          │
// │                     │
// │  listening to the   │ This page the listener
// │  stream             │ is visiting.
// │                     │
// │  https://x.y/listen │
// │                     │
// └─────────────────────┘

通过Web Audio API,我可以设置AudioContext,并可以通过WebRTC API将我的麦克风添加为源,但我不知道如何将其连接到另一个页面:

window.AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
const microphone = audioCtx.createMediaStreamSource(stream);
microphone.connect(audioCtx.destination);
});

";最佳实践";实现这种预期行为的方式

考虑使用History.pushState()更改浏览器URL。这样可以防止完全重新加载网页,从而保留录制/播放音频。这会触发popstate事件,您可以使用该事件动态更改页面上的某些内容,同时在DOM中保留其他内容(即音频播放器(。

示例

  • https://cøder.com/static/70886780/host
  • https://cøder.com/static/70886780/侦听

Web服务器配置

要拦截页面的第一次加载,后端web服务器需要为您定义的所有或特定路由提供相同的文件。例如,Nginx(用于上述示例(配置有:

location ~ ^(/static/70886780)/(host|listen|foo|bar)?$ {
add_header cache-control no-cache;
try_files $uri $1/index.html =404;
}

相关内容

最新更新