0

I wish to test from javascript within my html page if the following files exist or not:

http://www.focloir.ie/media/ei/sounds/ag_c.mp3  // exists
http://www.focloir.ie/media/ei/sounds/og_c.mp3  // doesn't exist

My html page is not on the same domain as the files above.

Is this possible?

I wish to solve this using only a single html file (no db or php etc.) since my project is just a simple prototype.

Baz
  • 12,713
  • 38
  • 145
  • 268
  • 2
    Yes it's possible, you write a serverside script that checks if the file exists, and call that with ajax from your own server. Javascript has no access to external .mp3 files, as it has a same origin policy. – adeneo May 14 '13 at 09:39
  • @adeneo OK so this is absolutely not solvable with just a single html file. In other words, I can't write a simple jsfiddle to do this lookup. – Baz May 14 '13 at 09:42
  • Not really, but you could always use YQL, or link to the file directly and see if it loads ? – adeneo May 14 '13 at 09:44
  • [JSON](http://en.wikipedia.org/wiki/JSONP) – Vignesh Vino May 14 '13 at 09:45
  • @adeneo What do you mean by "link to the file"? – Baz May 14 '13 at 09:48
  • @Vignesh Vino Can you please elaborate a little more regarding JSON? – Baz May 14 '13 at 09:48
  • You can do something like [this](http://jsfiddle.net/q8zQm/) ?? – adeneo May 14 '13 at 10:04
  • @adeneo your solution reminds me of the img `onload`/`onerror` technique. See for example http://stackoverflow.com/questions/3019077/detecting-a-image-404-in-javascript Does audio element also have `onload`? – Myrne Stol May 14 '13 at 10:13
  • @adeneo The error event isn't being triggered for me when the file doesn't exist. I'm testing using FF. http://jsfiddle.net/8QACt/ – Baz May 14 '13 at 12:37

1 Answers1

1

This looks promising, although super slow and ugly :)

var _word = "ag";
var _audio = Audio();

function update_src(audio, word) {
    if (audio.canPlayType('audio/mpeg;')) {
        audio.src = "http://www.focloir.ie/media/ei/sounds/" + word + "_c.mp3";
    } else {
        audio.src = "http://www.focloir.ie/media/ei/sounds_ogg/" + word + "_c.ogg";
    }
}

update_src(_audio, _word);
_audio.load();
_audio.addEventListener("durationchange", function () {
    alert("exits");
});
Baz
  • 12,713
  • 38
  • 145
  • 268