How to pass an audio stream to another page on the same website?

Viewed 284

I want to stream an audio source from a website /host to another page /listen on the same website.

The principle seems to be a bit like an online radio, the mini player on YouTube or streaming services like Tidal or Spotify, where you can listen to the music while switching to another page on the website but the listener is never visiting /host. The listener hears what the host is saying on /host. A simplified graphics could look like this:

// ┌─────────────────────┐
// │                     │
// │  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 │
// │                     │
// └─────────────────────┘

Via the Web Audio API I can setup an AudioContext and can add my microphone as a source via the WebRTC API, but I don't know how to connect it to another page:

    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);
    });

What would be the "best practice" way of achieving this expected behaviour?

1 Answers

Consider changing the browser URL with History.pushState(). This prevents a full reloading of the web page, which preserves the recording/playing audio. This triggers the popstate event, which you can use to dynamically change certain content on the page while preserving other content (i.e. audio player) within the DOM.

Examples

Web Server Config

To intercept the first-load of the page, the backend web server needs to serve the same file for all or specific routes you define. For example, Nginx (serves above examples) is configured with:

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