6

In safari 5, new Audio is not supported, so the error console displays :

TypeError : 'undefined' is not a constructor (evaluating 'new Audio')

How could I programatically know whether new Audio is supported by browser ?

madLokesh
  • 1,860
  • 23
  • 49
totoaussi
  • 712
  • 1
  • 11
  • 27

2 Answers2

3

I guess you might just try it...

var createAudio = function() {
 try {
    return new Audio(); 
 } catch(e) {
    return false;
 }
};
var audio = createAudio();
if(audio) {
  // start playing... or check formats etc.
}

In case there is exception, the Audio class does not exist and returns false.

For more detailed solution check Modernzr library: http://modernizr.com/docs/#audio

The related solution is here Detecting html5 audio support with Modernizr

Community
  • 1
  • 1
Tero Tolonen
  • 4,144
  • 4
  • 27
  • 32
2

There are multiple solutions to check if it exists.

Check that the type of Audio isn't "undefined".

if (typeof window.Audio !== "undefined")

Check if window has a property Audio.

if ("Audio" in window)

The below could generate an error.

if (window.Audio)

But, this code doesn't guarantee that it's a good Audio implementation. It could just be some random script doing this: window.Audio = 'http://link.to/some/mp3'.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44