如何在镀铬扩展中播放声音 [英] How can i play sound in a chrome extension
问题描述
我想在镀铬扩展中播放声音。我该怎么做?我应该在 myscript.js 文件中写什么?
I would like to play sound in chrome extension. How can I do it? What should I write in myscript.js file?
我试着用myscript.js写:
I tried to write in myscript.js:
var audio = new Audio("alarm.wav");
audio.play();
和:
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.
我的manifest.json文件:
My manifest.json file:
{
"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
}
如果我在myscript.js文件中添加按钮到站点,这个按钮效果很好,但是我无法播放声音。我的音频文件是mp3,与manifest.json和myscript.js在同一文件夹中,我的myscript.js是:
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:
var myAudio = new Audio();
myAudio.src = "alarm.mp3";
myAudio.play();
推荐答案
使用JavaScript播放声音/音乐的最简单方法是使用音频
对象:您只需要在扩展文件夹中放置要播放的文件,就可以这样播放:
The easiest way to play some sound/music using JavaScript is by using an Audio
object: you just need to have the file you want to play inside your extension folder, and you can play it like this:
var myAudio = new Audio(chrome.runtime.getURL("path/to/file.mp3"));
myAudio.play();
您可以使用 play()
进行游戏,暂停使用 pause()
。
You can play using play()
and pause using pause()
.
请记住,如果你想在内容脚本(或任何地方)播放声音否则不在 chrome:// extension
URL下,你必须在 web_accessible_resources
清单字段:
Remember that if you want to play the sound in a content script (or anywhere else that is not under a chrome://extension
URL) you'll have to declare the audio file in the web_accessible_resources
manifest field:
"web_accessible_resources": [
"path/to/file.mp3"
]
工作示例
您可以下载我从 此处 即可。当您单击stackoverflow.com页面内的任何内容时,它会通过内容脚本播放声音。
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.
这篇关于如何在镀铬扩展中播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!