sound-notification.html 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <dom-module id="sound-notification">
  2. <template>
  3. <audio id="blop" preload="auto" autobuffer="true">
  4. <source src="/sounds/blop.mp3" id="mp3Source" type="audio/mpeg">
  5. <source src="/sounds/blop.ogg" id="oggSource" type="audio/ogg">
  6. </audio>
  7. </template>
  8. </dom-module>
  9. <script>
  10. 'use strict';
  11. Polymer({
  12. is: 'sound-notification',
  13. properties: {
  14. volumes: {
  15. value: {
  16. 'blop': 0.8,
  17. }
  18. }
  19. },
  20. attached: function() {
  21. // mobiles don't like autoplay - the first play must be triggert by user interaction
  22. var that = this;
  23. var hackListener = function() {
  24. that.volumes.blop = 0.1;
  25. that.play();
  26. document.body.removeEventListener('touchstart', hackListener, false);
  27. that.volumes.blop = 0.8;
  28. };
  29. document.body.addEventListener('touchstart', hackListener, false);
  30. },
  31. play: function() {
  32. this._play('blop');
  33. },
  34. _play: function(sound) {
  35. var audio = this.$[sound];
  36. if (!audio) {
  37. console.warn('audio ', sound, ' doesn\'t exist.');
  38. return;
  39. }
  40. if (audio.readyState > 0) {
  41. audio.volume = this.volumes[sound];
  42. audio.pause();
  43. audio.currentTime = 0;
  44. audio.play();
  45. } else {
  46. console.warn('audio not ready yet...');
  47. //play when ready
  48. //TODO: play only if ready within next ~500ms
  49. audio.addEventListener('loadedmetadata', function() {
  50. this._play(sound);
  51. }.bind(this), false);
  52. }
  53. }
  54. });
  55. </script>