如何在扩展中播放音频? [英] How to play audio in an extension?

查看:128
本文介绍了如何在扩展中播放音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  AudioObj =新的音频; 

将会返回Audio is not definied

<我也尝试了经典的修复:

  var audio = require(audio); 

但没有运气。我可以在 main.js 的扩展的其他部分添加音频播放,就像其中的一些内容脚本一样,但也许有一个更简单更优雅的解决方案。 / p>

解决方案 音频> HTML元素 - 仅适用于绑定到文档的上下文。 SDK模块在没有文档的上下文中执行,因此不包括这个DOM方法。解决方法是通过 about:blank /packages/addon-kit/page-worker.htmlrel =nofollow> page-worker 模块并在那里注入内容脚本。然后,您可以发送消息到该内容脚本,并让它随时为您播放音频。



另一种方法是使用
$ b

var {Cc,Ci} = require(chrome);
var sound = Cc [@ mozilla.org/sound;1\"].createInstance(Ci.nsisound);
var uri = Cc [@ mozilla.org/network/io-service;1]
.getService(Ci.nsIIOService)
.newURI(self.data.url(.. 。),null,null);

sound.play(uri);

注意 nsISound 很可能会被弃用。这是一个旧的API,不如HTML5音频。


AudioObj = new Audio;

will return "Audio is not definied"

I also tried the classic fix:

var audio = require("audio");

but with no luck. I could add audio playback in some other part of the extension than in main.js, like some content script where it works, but maybe there is a simpler and elegant solution.

解决方案

new Audio creates a new <audio> HTML element - this only works in a context that is bound to a document. SDK modules execute in a context however that has no document, consequently no DOM methods will work including this one. A work-around would be loading about:blank via page-worker module and injecting a content script there. You could then send messages to that content script and let it play audio for you whenever you need it.

The alternative would be using nsISound.play(), something along these lines:

var {Cc, Ci} = require("chrome");
var sound = Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound);
var uri = Cc["@mozilla.org/network/io-service;1"]
            .getService(Ci.nsIIOService)
            .newURI(self.data.url(...), null, null);

sound.play(uri);

Note that nsISound is likely to be deprecated soon. It is an old API that is inferior to HTML5 audio.

这篇关于如何在扩展中播放音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆