m3u.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #!./bin/python3
  2. import os
  3. import threading
  4. import time
  5. from handler import EVENT_LEFT
  6. from handler.listhandler import BaseListHandler
  7. from handler.lib.pymplb import MPlayer
  8. class M3UHandler(BaseListHandler):
  9. def __init__(self, config, display):
  10. super().__init__(config, display)
  11. self._mplayer = None
  12. self._mplayer_watcher = None
  13. self.is_playing = False
  14. self._last_event = time.time()
  15. def setPlaylistItem(self, item):
  16. '''
  17. Called with the selected item.
  18. '''
  19. self.item = item
  20. path = item["path"]
  21. items = []
  22. with open(path) as f:
  23. for line in f:
  24. item_path = str(line).strip()
  25. if not item_path.startswith("#"):
  26. items.append({
  27. "name" : self.toDisplayName(os.path.basename(item_path)),
  28. "path" : os.path.join(os.path.dirname(path), item_path)
  29. })
  30. if self._mplayer is None:
  31. self._mplayer = MPlayer()
  32. self.setItems(items)
  33. self._mplayer_watcher = threading.Thread(target=self._watch_mplayer, daemon=True)
  34. self._mplayer_watcher.start()
  35. self.is_playing = False
  36. def itemSelected(self, item):
  37. self._mplayer.loadfile(item["path"])
  38. self.is_playing = True
  39. def stop(self):
  40. '''
  41. Called when the handler should stop.
  42. '''
  43. if self._mplayer is not None:
  44. self._mplayer.quit()
  45. self._mplayer = None
  46. self._mplayer_watcher = None
  47. def emitEvent(self, event):
  48. '''
  49. Called when an event has happened.
  50. '''
  51. # Clock the time so the thread can hold off if there
  52. # was a recent user event
  53. self._last_event = time.time()
  54. if event == EVENT_LEFT and self.is_playing:
  55. self._mplayer.stop()
  56. self.is_playing = False
  57. return
  58. super().emitEvent(event)
  59. def _watch_mplayer(self):
  60. '''
  61. Thread to watch mplayer and advance the playlist.
  62. '''
  63. while self._mplayer_watcher is not None:
  64. try:
  65. time.sleep(0.5)
  66. if self._mplayer:
  67. playing_path = self._mplayer.p_path
  68. # Only do something in the thread if the last user
  69. # input is at least 3 seconds ago
  70. if time.time() - self._last_event > 3:
  71. # Advance to the next item if we are playing music
  72. if self.is_playing and playing_path == "(null)":
  73. self.nextItem()
  74. except Exception as e:
  75. print("Error watching player:", e)