summaryrefslogtreecommitdiff
path: root/example-scripts/gstreamer/source-nostream-music-from-folder.py
blob: fb09247490ef01f90e5d8a818f6a1c2cb6a27da8 (plain)
  1. #!/usr/bin/env python3
  2. import os, sys, gi, signal
  3. import argparse, logging, pyinotify
  4. gi.require_version('Gst', '1.0')
  5. from gi.repository import Gst, GObject, GLib
  6. # init GObject & Co. before importing local classes
  7. GObject.threads_init()
  8. Gst.init([])
  9. class Directory(object):
  10. def __init__(self, path):
  11. self.log = logging.getLogger('Directory')
  12. self.path = path
  13. self.scheduled = False
  14. self.rescan()
  15. self.log.info('setting up inotify watch for %s', self.path)
  16. wm = pyinotify.WatchManager()
  17. notifier = pyinotify.Notifier(wm,
  18. timeout=10,
  19. default_proc_fun=self.inotify_callback)
  20. wm.add_watch(
  21. self.path,
  22. #pyinotify.ALL_EVENTS,
  23. pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY,
  24. rec=True)
  25. GLib.io_add_watch(
  26. notifier._fd,
  27. GLib.IO_IN,
  28. self.io_callback,
  29. notifier)
  30. def inotify_callback(self, notifier):
  31. self.log.info('inotify callback %s: %s', notifier.maskname, notifier.pathname)
  32. if not self.scheduled:
  33. self.scheduled = True
  34. GLib.timeout_add(100, self.rescan)
  35. return True
  36. def io_callback(self, source, condition, notifier):
  37. notifier.process_events()
  38. while notifier.check_events():
  39. notifier.read_events()
  40. notifier.process_events()
  41. return True
  42. def is_playable_file(self, filepath):
  43. root, ext = os.path.splitext(filepath)
  44. return ext in ['.mp3', '.ogg', '.oga', '.wav', '.m4a', '.flac', 'self.opus']
  45. def rescan(self):
  46. self.log.info('scanning directory %s', self.path)
  47. self.scheduled = False
  48. all_files = []
  49. for root, dirs, files in os.walk(self.path):
  50. files = filter(self.is_playable_file, files)
  51. files = map(lambda f: os.path.join(root, f), files)
  52. files = list(files)
  53. self.log.debug('found directory %s: %u playable file(s)', root, len(files))
  54. all_files.extend(files)
  55. self.log.info('found %u playable files', len(all_files))
  56. self.files = all_files
  57. class LoopSource(object):
  58. def __init__(self, directory):
  59. self.log = logging.getLogger('LoopSource')
  60. pipeline = """
  61. audioresample name=join !
  62. audioconvert !
  63. audio/x-raw,format=S16LE,channels=2,layout=interleaved,rate=48000 !
  64. matroskamux !
  65. tcpclientsink host=localhost port=18000
  66. """
  67. self.pipeline = Gst.parse_launch(pipeline)
  68. # https://c3voc.mazdermind.de/testfiles/music-snippets.tar
  69. self.src = Gst.ElementFactory.make('uridecodebin', None)
  70. self.src.set_property('uri', 'file:///home/peter/Music/pieces/001 - Bruno Mars - Grenade.mp3');
  71. self.src.connect('pad-added', self.on_pad_added)
  72. self.pipeline.add(self.src)
  73. self.joinpad = self.pipeline.get_by_name('join').get_static_pad('sink')
  74. # Binding End-of-Stream-Signal on Source-Pipeline
  75. self.pipeline.bus.add_signal_watch()
  76. self.pipeline.bus.connect("message::eos", self.on_eos)
  77. self.pipeline.bus.connect("message::error", self.on_error)
  78. print("playing")
  79. self.pipeline.set_state(Gst.State.PLAYING)
  80. def on_pad_added(self, src, pad):
  81. print('New Pad: '+str(pad))
  82. pad.add_probe(Gst.PadProbeType.EVENT_DOWNSTREAM | Gst.PadProbeType.BLOCK, self.on_pad_event)
  83. if self.joinpad.is_linked():
  84. self.joinpad.unlink(self.joinpad.get_peer())
  85. pad.link(self.joinpad)
  86. def on_pad_event(self, pad, info):
  87. event = info.get_event()
  88. print('Pad Event: '+str(event.type)+' on Pad '+str(pad))
  89. if event.type == Gst.EventType.EOS:
  90. print('Is an EOS event, dropping & unlinking')
  91. GObject.idle_add(self.next_track)
  92. return Gst.PadProbeReturn.DROP
  93. return Gst.PadProbeReturn.PASS
  94. def next_track(self):
  95. print("next_track")
  96. self.pipeline.set_state(Gst.State.READY)
  97. self.src.set_property('uri', 'file:///home/peter/Music/pieces/003 - Taio Cruz feat. Kylie Minogue - Higher.mp3');
  98. self.pipeline.set_state(Gst.State.PLAYING)
  99. return False
  100. def on_eos(self, bus, message):
  101. print('Received EOS-Signal')
  102. sys.exit(1)
  103. def on_error(self, bus, message):
  104. print('Received Error-Signal')
  105. (error, debug) = message.parse_error()
  106. print('Error-Details: #%u: %s' % (error.code, debug))
  107. sys.exit(1)
  108. def main():
  109. logging.basicConfig(
  110. level=logging.DEBUG,
  111. format='%(levelname)8s %(name)s: %(message)s')
  112. signal.signal(signal.SIGINT, signal.SIG_DFL)
  113. parser = argparse.ArgumentParser(description='Voctocore Music-Source')
  114. parser.add_argument('directory')
  115. args = parser.parse_args()
  116. print('Playing from Directory '+args.directory)
  117. directory = Directory(args.directory)
  118. #src = LoopSource(directory)
  119. mainloop = GObject.MainLoop()
  120. try:
  121. mainloop.run()
  122. except KeyboardInterrupt:
  123. print('Terminated via Ctrl-C')
  124. if __name__ == '__main__':
  125. main()