1

For Javascript:

Is it possible for my browser to play some sort of sound/music when a certain image appears? Could it perhaps play an mp3 file in my music library? Right now, the best I can do is:

if (document.getElementById("happyface")) {
    window.alert("Attention: Happy face detected.");
    }

I should also mention that I have the page constantly refreshing itself, so a loop isn't necessary (at least, I don't think so).

  • 4
    Page that _"constantly refreshing itself"_ and plays music... sounds like you gonna suffer from too much traffic really soon. – gdoron Jul 19 '13 at 11:48
  • I tried looking around before asking, but couldn't find much. Quentin, is it possible to play a local audio file without importing any additional libraries? – user2599295 Jul 19 '13 at 11:56
  • gdoron, it's not actually my own site, so I don't need to worry about traffic just yet. And the script pauses when the particular image of interest is detected. Also, I should also mention that this is a "scriptname.user.js" type of file. As an complete amateur, I actually don't know if that's obvious. – user2599295 Jul 19 '13 at 11:59
  • Perhaps a better way to word my question is: "How can I get my userscript in Google Chrome to play my 3 second audio file if (document.location.href == 'http://facebook.com')"? – user2599295 Jul 19 '13 at 12:05

1 Answers1

3

Just use the audio tag for that:

function sound(){
    var audio = document.createElement("audio");
    audio.src = "your_path_to_soundfile.wav";
    audio.addEventListener("ended", function () {
        document.removeChild(this);
    }, false);
    audio.play();   
}

if (document.getElementById("happyface")) {
    sound();
}
Jannik Weichert
  • 1,623
  • 16
  • 28
  • I think that exactly what I'm looking for, but the only problem is that I can't seem to get it to start. This pops up in the console: "Not allowed to load local resource: Not allowed to load local resource: file:///C:/Users/Admin/Music/bicycle_bell.wav " – user2599295 Jul 19 '13 at 12:27
  • You cannot access local filesystem by default from javascript. Try the code with a weblink to a sound like "http://yourpath.com/sound.wav" – Jannik Weichert Jul 19 '13 at 12:40