How can I play a sound within a Greasemonkey script?

十年热恋 提交于 2019-12-22 10:53:36

问题


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!


回答1:


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!');
  }
}



回答2:


Inorder to play a sound in GreaseMonkey script, you have to follow these basic steps:

Step 1: Create an element of type "Audio"

Step 2: Assign the source property to the file location.

var audio = document.createElement("audio");
audio.src = "https://dl.dropbox.com/u/7079101/coin.mp3";



回答3:


Here's a solution

var audioformsg = new Audio();
audioformsg.src = 'http://www.podst.ru/pix/user_files/2/5564/Click_08.mp3';
audioformsg.autoplay = true;

from code https://greasyfork.org/zh-CN/scripts/8149-sound-for-message/code



来源:https://stackoverflow.com/questions/27862073/how-can-i-play-a-sound-within-a-greasemonkey-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!