Search code examples
typescriptangular5audiocontextwebkitaudiocontext

AudioContext issue on Safari


I'm trying to use AudioContext in my typescript file for an Angular 5 app. It works great on Chrome, doesn't work on Safari. Everything I see by googling says to use window.webkitAudioContext but that immediately blows up when the typescript compiler runs saying that it doesn't exist on type Window.

let context = new AudioContext();
let source = context.createBufferSource();
context
    .decodeAudioData(event.body)
    .then(x => {
        source.buffer = x;
        source.connect(context.destination);
        source.start(0);
    });

Solution

  • You should extend the Window interface and then augment the window object.

    Asuming you're using angular-cli, add the following to your typings.d.ts file:

    declare interface Window {
      AudioContext: AudioContext;
    }
    

    Then inside your polyfills.ts file you could set the AudioContext attribute:

    window.AudioContext = window.AudioContext || window.webkitAudioContext;