简体   繁体   中英

Play sound when download finishes

Hey guys am new to chrome extension development.I have decided to made a chrome extension which is same as the download manager. I am trying to add a feature like when the download item is finished an audio must be played. So i have tried researching about this and found out onCreated event.I think thisis what i have wanted..

So i have tried the code like

DownloadItem.prototype.onCreated = function() {
  if (this.state == 'complete') {
var c = new Audio('Link to an audio source');
c.play();
}

But it didnt do anything.I am unable to hear the sound after the item is finished downloading.

Here is my manifest.json .

As per the edit..

The main code which plays role in audio is

popup.js

if (chrome.downloads) {
  DownloadManager.loadItems();
  chrome.downloads.onCreated.addListener(function(item) {
DownloadManager.getOrCreate(item);
DownloadManager.showNew();
DownloadManager.startPollingProgress();
  });

  chrome.downloads.onChanged.addListener(function(delta) {
var item = DownloadManager.getItem(delta.id);
if (item) {
  item.onChanged(delta);
}
  });

  chrome.downloads.onErased.addListener(function(id) {
var item = DownloadManager.getItem(id);
if (!item) {
  return;
}
item.onErased();
DownloadManager.loadItems();
  });

  chrome.downloads.onChanged.addListener(function(delta) {
  if (delta.state.current == "complete") {
   var c = new Audio('http://www.html5rocks.com/en/tutorials/audio/quick/test.mp3');
c.play();
}
});

manifest

{"name": "__MSG_extName__",
 "version": "0.3",
 "manifest_version": 2,
 "description": "__MSG_extDesc__",
 "icons": {"128": "icon128.png"},
 "browser_action": {
   "default_icon": {
 "19": "icon19.png",
 "38": "icon38.png"},
   "default_title": "__MSG_extName__",
   "default_popup": "popup.html"},
 "background": {"persistent": false, "scripts": ["background.js"]},
 "default_locale": "en",
 "optional_permissions": ["management"],
 "permissions": ["downloads", "downloads.open", "downloads.shelf", "notifications"]}

The whole code can be found here

First off, it's a wrong event. onCreated obviously is supposed to fire when a download is created , and so it is guaranteed not to be completed. And it won't fire again.

Next off, you're using Chrome API events wrong.

  1. They are not attached to a particular DownloadItem , but are dispatched globally, ie chrome.downloads.onCreated .

  2. An event is not a function to be executed (like onclick on an HTML element), it's an object with a method addListener to attach handlers.

Putting it together, and taking a look at chrome.downloads API , you need this:

chrome.downloads.onChanged.addListener(function(delta) {
  if (delta.state.current == "complete") {
    // Play sound
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM