bookmark-audio-fragment/app/scripts/ contentscript.js
89 lines
2.2 KiB

  1. import * as WaveformPlaylist from 'waveform-playlist';
  2. import delay from 'delay';
  3. async function init() {
  4. document.body.innerHTML = `
  5. <main>
  6. <div id="controls">
  7. <button id="playpause">⏯</button>
  8. <div>
  9. <label for="volume" id="volume-label">🔊</label>
  10. <input type="range" min="0" max="100" value="100" id="volume" />
  11. </div>
  12. </div>
  13. <div id="container">
  14. </div>
  15. </main>
  16. `;
  17. const playlist = WaveformPlaylist.init({
  18. container: document.getElementById('container'),
  19. timescale: true,
  20. waveHeight: 100,
  21. state: 'select',
  22. });
  23. const eventEmitter = playlist.getEventEmitter();
  24. // Hook up play/pause and volume inputs
  25. const playpauseEl = document.getElementById('playpause');
  26. const volumeEl = document.getElementById('volume');
  27. playpauseEl.addEventListener('click',
  28. e => eventEmitter.emit(playlist.isPlaying() ? 'pause' : 'play')
  29. );
  30. volumeEl.addEventListener('input',
  31. e => eventEmitter.emit("mastervolumechange", e.target.value)
  32. );
  33. // Read target fragment from URL
  34. let start, end;
  35. async function setFragmentToSelection() {
  36. const fragmentIdentifier = window.location.hash;
  37. if (fragmentIdentifier) {
  38. const match = fragmentIdentifier.match(/#t=(\d+(?:\.\d+)?)?(?:,(\d+(?:\.\d+)?))?/);
  39. if (match) {
  40. if (match[1] !== undefined) {
  41. start = Number.parseFloat(match[1]);
  42. }
  43. if (match[2] !== undefined) {
  44. end = Number.parseFloat(match[2]);
  45. }
  46. }
  47. }
  48. // Emit event to update selection in player
  49. eventEmitter.emit('select', start, end);
  50. }
  51. // Bind window hash change to update player
  52. window.addEventListener('hashchange', async function() {
  53. if(playlist.isPlaying()) {
  54. eventEmitter.emit('stop')
  55. // pause needs a small delay, coz the lib doesn't
  56. // update player view (drawRequest) when isPlaying() = true.
  57. await delay(10);
  58. }
  59. await setFragmentToSelection();
  60. eventEmitter.emit('play');
  61. });
  62. // Load Playlist
  63. await playlist.load([{
  64. src: document.URL
  65. }]);
  66. // update start & end for initial load
  67. setFragmentToSelection();
  68. // Start playing. A tiny delay seems needed in Firefox to show the cursor at the right place.
  69. requestAnimationFrame(() => eventEmitter.emit('play'));
  70. }
  71. init();