music.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import subprocess
  2. import os
  3. import base
  4. import output
  5. _FOLDER = '/mnt/nas/music/albums'
  6. class Music(base.BaseService):
  7. folders = None
  8. current_process = None
  9. def __init__(self):
  10. self.initialized = False
  11. def init(self):
  12. folders = [unicode(os.path.join(_FOLDER, f).decode('utf-8')) for f in os.listdir(_FOLDER)]
  13. folders = [f for f in folders if os.path.isdir(f)]
  14. self.folders = {os.path.basename(f).lower(): f for f in folders}
  15. self.initialized = True
  16. def _search(self, tokens):
  17. if not tokens:
  18. return
  19. eligible = self.folders
  20. for t in tokens:
  21. t = t.lower()
  22. eligible = {f: v for f, v in eligible.iteritems() if t in f}
  23. output.debug('tokens: %s; eligible: %s', tokens, eligible.keys())
  24. if eligible:
  25. return eligible[eligible.keys()[0]]
  26. def stop(self):
  27. if self.current_process:
  28. self.current_process.terminate()
  29. self.current_process = None
  30. def call(self):
  31. tokens = ears.listen(pause_threshold=3, preferred_phrases=self.folders.keys()[:300])
  32. f = self._search(tokens)
  33. if f:
  34. output.debug('playing %s' % f)
  35. self.current_process = subprocess.Popen(['cvlc', '-Z', f, ])
  36. else:
  37. output.failure()
  38. def help(self):
  39. return 'Plays music. Example: "play Coldplay".'