11

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);
    });
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Gargoyle
  • 9,590
  • 16
  • 80
  • 145

4 Answers4

6

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;
cyr_x
  • 13,987
  • 2
  • 32
  • 46
3

You could just cast window to any:

(window as any).AudioContext = (window as any).AudioContext || (window as any).webkitAudioContext;
let context = new AudioContext();
sakai
  • 163
  • 7
2

You have to add the desired properties to the Window interface in the global namespace.

declare global {
  interface Window {
    AudioContext: typeof AudioContext;
    webkitAudioContext: typeof AudioContext;
  }
}

const context = new (window.AudioContext || window.webkitAudioContext)();
CalMlynarczyk
  • 705
  • 2
  • 7
  • 12
1

I settled on this one-liner:

const audioContext: AudioContext = new (window["AudioContext"] || window["webkitAudioContext"])();
Draghon
  • 347
  • 3
  • 9
  • This looks simple but unfortunately doesn't compile: `Element implicitly has an 'any' type because index expression is not of type 'number'. TS7015` at the second term in the expression. – tromgy Dec 28 '20 at 00:53