如何在镀铬扩展中播放声音

编程入门 行业动态 更新时间:2024-10-18 16:48:52
本文介绍了如何在镀铬扩展中播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在镀铬扩展中播放声音。我该怎么做?我应该在 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": [ "site1/", "site2/" ], "content_scripts": [ { "matches": ["site1/", "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页面内的任何内容时,它会通过内容脚本播放声音。

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 page.

更多推荐

如何在镀铬扩展中播放声音

本文发布于:2023-11-14 15:16:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587769.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:镀铬   声音   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!