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);
});
Yes, Safari supports the Web Audio API only on version 6.1 or above. – Marco Bonelli Mar 31, 2015 at 18:34 Applesays the latest version is 5.1.7. – Phillip Senn Mar 31, 2015 at 19:01 1 That only applies to Safari for Windows and Mac OS X (or lower).
Latest stable Chrome: 'webkitAudioContext' is deprecated. Please use 'AudioContext' instead.. Seems that AudioContext is now prefix-less in all major modern browsers. No idea about Safari since the Windows version hasn't been updated since 2012 – bryc Jul 25, 2015 at 19:34
AudioContextfeature detection To be sure you can use the Web Audio API on any browser which supportsit, you can use feature detection with relative fallbacks to the vendor-prefixed objects. In case the AudioContextobject is not supported, you'll halt the execution of your script and alert the user. Here's an example:
The Web Audio API (id est AudioContext) is not supported by all the browsers. Some browsers may have it prefixed with their vendor prefix, but older browsers do not support it at all. Therefore, to answer your question: you cannot use the AudioContext on all the browsers.
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;
You could just cast window
to any
:
(window as any).AudioContext = (window as any).AudioContext || (window as any).webkitAudioContext;
let context = new AudioContext();
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)();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With