user2104556
user2104556

Reputation: 1

Use chrome.extension.getBackgroundPage() to play an audio file

I’m trying to develop a basic Chrome extension that plays a sound, based on a speech input event (everything happens in the background).

Here’s my manifest

{
  "manifest_version" : 2,
  "name"             : "Test123",
  "version"          : "1.0",
  "description"      : "My audio extension",

  "icons"            : {
    "128"              : "icon.jpg"
  },

  "permissions"      : [
    "experimental",
    "background"
  ],

  "background"       : {
    "persistent"       : true,
    "scripts"          : [
      "bg.js"
    ]
  },
}

In bg.js, I get the window object with var chrome.extension.getBackgroundPage();, but I can’t figure what to do from there.

How can I play an audio file?

Upvotes: 0

Views: 3594

Answers (1)

Paul Fournel
Paul Fournel

Reputation: 11207

Here is the solution !

First of all, loading the music file in a background page is the good solution. But you have to trigger the execution of your audio file from the popup page. Here is the script :

 // In popup.html 
 <div id="play-it">Play</div>

 // dont forget to use an external script file
 $('#play-it').click(function(){
     chrome.extension.sendMessage({action: "play"})
 });

Then in the bg.js you will listen to the Message

 // In bg.js
 var audioElement = document.createElement('audio');
 audioElement.setAttribute("preload", "auto");
 audioElement.autobuffer = true;

 var source1 = document.createElement('source');
 source1.type= 'audio/mpeg';
 source1.src= 'http://lezotre.free.fr/Mp3/disco.mp3';
 audioElement.appendChild(source1);

 chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
      if (request.action == "play"){
          audioElement.load;
          audioElement.play();
      }
});

You will find more information on message passing on the official google chrome documentation : http://developer.chrome.com/extensions/messaging.html

Upvotes: 2

Related Questions