javascript 如何在 chrome 扩展中播放声音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27496465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:33:31  来源:igfitidea点击:

How can i play sound in a chrome extension

javascriptgoogle-chromegoogle-chrome-extension

提问by Przemys?aw Niedziela

I would like to play sound in chrome extension. How can I do it? What should I write in myscript.jsfile?

我想在 chrome 扩展中播放声音。我该怎么做?我应该在myscript.js文件中写什么?

I tried to write in myscript.js:

我试着在 myscript.js 中写:

var audio = new Audio("alarm.wav");
audio.play();

and:

和:

document.write('<audio id="player" src="alarm.wav" >');
document.getElementById('player').play();

but it does not work. I did not add anything more, so there are no unfulfilled conditions.

但它不起作用。我没有再添加任何东西,所以没有未满足的条件。

My manifest.json file:

我的 manifest.json 文件:

{
  "name": "Alarm",
  "version": "1.0.0",
  "icons": {"64": "icon64.png"},
  "permissions": [
    "http://site1/",
    "http://site2/"
  ],
  "content_scripts": [
    {
      "matches": ["http://site1/", "http://site2/"],
      "js": ["myscript.js"],
      "run_at": "document_end"
    }
  ],
  "manifest_version": 2
}

If I add button to site in myscript.js file, this button works well, but i can't play sound. My audio file is mp3 and is in the same folder as manifest.json and myscript.js, and my myscript.js is:

如果我在 myscript.js 文件中向站点添加按钮,则此按钮运行良好,但无法播放声音。我的音频文件是 mp3,与 manifest.json 和 myscript.js 在同一个文件夹中,我的 myscript.js 是:

var myAudio = new Audio();
myAudio.src = "alarm.mp3";
myAudio.play();

回答by Marco Bonelli

The easiest way to play some sound/music using JavaScript is by using an Audioobject: you just need to have the file you want to play inside your extension folder, and you can play it like this:

使用 JavaScript 播放一些声音/音乐的最简单方法是使用Audio对象:您只需要将要播放的文件放在扩展文件夹中,您就可以像这样播放它:

var myAudio = new Audio(chrome.runtime.getURL("path/to/file.mp3"));
myAudio.play();

You can play using play()and pause using pause().

您可以使用播放play()和暂停使用pause()

Remember that if you want to play the sound in a content script (or anywhere else that is not under a chrome://extensionURL) you'll have to declare the audio file in the web_accessible_resourcesmanifest field:

请记住,如果您想在内容脚本(或不在chrome://extensionURL下的任何其他地方)播放声音,则必须在web_accessible_resources清单字段中声明音频文件:

"web_accessible_resources": [
    "path/to/file.mp3"
]


Working example

工作示例

You can download a test extension I made from HERE. It plays a sound through a content script when you click anything inside a stackoverflow.com page.

你可以下载我从这里制作的测试扩展。当您单击 stackoverflow.com 页面内的任何内容时,它会通过内容脚本播放声音。