Back to KB
Difficulty
Intermediate
Read Time
5 min

Analyzing HLS Audio Streams with Web Audio API and hls.js

By Codcompass Team··5 min read

When working with Web Audio API and HTML media elements, developers frequently encounter three main issues:

  1. The MediaElementAudioSourceNode Duplication Error

The most common error looks like this:

Cannot create multiple MediaElementAudioSourceNode from the same HTMLMediaElement

Enter fullscreen mode Exit fullscreen mode

This happens because browsers allow creating only one MediaElementAudioSourceNode per <video> or <audio> element. Attempting to create a second one will throw an error, and the original element may lose its audio.

  1. Autoplay Policy Restrictions

Modern browsers block automatic audio playback before user interaction. AudioContext is created in a suspended state, and you must explicitly call resume() after a user gesture (click, tap).

  1. HLS Manifest Loading Synchronization

The HLS manifest loads asynchronously through hls.js. If you create MediaElementAudioSourceNode before the manifest fully loads and attaches to the video element, you'll get silent audio or initialization errors.

The Solution: Singleton Pattern for AudioContext Management

To guarantee a single AudioContext instance and correct MediaElementAudioSourceNode functionality, we use the Singleton pattern. This ensures:

  • Single instance of AudioContext per application
  • Single MediaElementAudioSourceNode per media element
  • Centralized audio graph state management
  • Easy reusability across app components

Basic Implementation

export class HlsAudioService {
  private static instance: HlsAudioService;
  public audioContext: AudioContext;
  public source?: MediaElementAudioSourceNode;
  public splitter?: ChannelSplitterNode;
  public analysers: AnalyserNode[] = [];

  private constructor() {
    const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext;
    this.audioContext = new AudioContextClass();
  }

  static getInstance(): HlsAudioService {
    if (!HlsAudioService.instance) {
      HlsAudioService.instance = new H

🎉 Mid-Year Sale — Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register — Start Free Trial

7-day free trial · Cancel anytime · 30-day money-back