Search code examples
javascriptaudiogreasemonkey

How can I play a sound within a Greasemonkey script?


How can I play a sound within a Greasemonkey script?

What I'm trying to do currently is to play a sound whenever a condition is reached, something like:

// ==UserScript==
// @name Sound Alert
// @namespace example.com
// @include example.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @version 1
// @grant none
// ==/UserScript==

sound = new Audio("https://dl.dropbox.com/u/7079101/coin.mp3");

for (var i = 0; i <= 10; i++) {
  if (i === 10) {
    // Play a sound when i === 10
    sound.play();
  } else {
    console.log('Not yet!');
  }
}

How can I do this? Is there any way to do so? The code above isn't working!


Solution

  • Well, it seems like asking improves the possibility of finding out the correct answer for a problem (hehehe).

    Here's my solution:

    // ==UserScript==
    // @name    Sound Alert
    // @include http://YOUR_SERVER.COM/YOUR_PATH/*
    // @grant   none
    // ==/UserScript==
    
    var player = document.createElement('audio');
    player.src = 'https://dl.dropbox.com/u/7079101/coin.mp3';
    player.preload = 'auto';
    
    for (var i = 0; i <= 10; i++) {
      if (i === 10) {
        // Play a sound when i === 10
        player.play();
      } else {
        console.log('Not yet!');
      }
    }