Python gi.repository.GObject.MainLoop() Examples

The following are 30 code examples of gi.repository.GObject.MainLoop(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.GObject , or try the search function .
Example #1
Source File: bt-audio.py    From bt-audio with GNU General Public License v3.0 7 votes vote down vote up
def main():

    global args
    args = argparser.parse_args()

    bluez = Bluez()

    adapt = bluez.getAdapter(args.adapter)

    if not adapt:
        print("Adapter " + args.adapter + " not found")
        return

    adapt.powerSet(True)
    adapt.discoverableSet(True)
    adapt.mediaEndpointRegisterSBC()
    if args.aac_enabled:
        adapt.mediaEndpointRegisterAAC()


    Gst.init(None)
    GObject.threads_init()
    mainloop = GObject.MainLoop()
    mainloop.run()
    return 
Example #2
Source File: decoder_test.py    From Dragonfire with MIT License 6 votes vote down vote up
def setUpClass(cls):
        # voxforge/tri2b_mmi_b0.05 model:
        decoder_conf = {
            "model": "models/english/final.mdl",
            "lda-mat": "models/english/final.mat",
            "word-syms": "models/english/words.txt",
            "fst": "models/english/HCLG.fst",
            "silence-phones": "6"
        }
        cls.decoder_pipeline = DecoderPipeline({"decoder": decoder_conf})
        cls.words = []
        cls.finished = False

        cls.decoder_pipeline.set_word_handler(cls.word_getter)
        cls.decoder_pipeline.set_eos_handler(cls.set_finished, cls.finished)

        loop = GObject.MainLoop()
        thread.start_new_thread(loop.run, ()) 
Example #3
Source File: kaldi.py    From Dragonfire with MIT License 6 votes vote down vote up
def __init__(self):
        # logging.basicConfig(level=logging.INFO)

        # voxforge/tri2b_mmi_b0.05 model:
        decoder_conf = {
            "model": ENGLISH_MODEL_PATH + "final.mdl",
            "lda-mat": ENGLISH_MODEL_PATH + "final.mat",
            "word-syms": ENGLISH_MODEL_PATH + "words.txt",
            "fst": ENGLISH_MODEL_PATH + "HCLG.fst",
            "silence-phones": "6"
        }
        self.decoder_pipeline = DecoderPipeline({"decoder": decoder_conf})
        self.__class__.words = []
        self.__class__.finished = False

        self.decoder_pipeline.set_word_handler(self.word_getter)
        self.decoder_pipeline.set_eos_handler(self.set_finished, self.finished)

        GObject.threads_init()
        self.loop = GObject.MainLoop()
        self.gi_thread = Thread(target=self.loop.run, args=())
        self.gi_thread.start() 
Example #4
Source File: daemon.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        setproctitle.setproctitle('pulseaudio-daemon')
        self.mainloop = GObject.MainLoop()
        self.processes = []
        self.check_id = None
        self.is_checking = False

        self._check_processes()

        signals = (
            ('NameOwnerChanged', 'org.freedesktop.DBus.{}',
                self.on_name_owner_changed),
        )
        self.bus = dbus.SystemBus()
        self.core = self.bus.get_object('org.freedesktop.DBus', '/')
        for sig_name, interface, sig_handler in signals:
            self.bus.add_signal_receiver(sig_handler, sig_name) 
Example #5
Source File: mdns.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def run(self, ttl=None):
        if self.host:
            self.zeroconf = zeroconf.Zeroconf(interfaces=[self.host])
        else:
            self.zeroconf = zeroconf.Zeroconf()
        zeroconf.ServiceBrowser(self.zeroconf, self.domain, MDNSHandler(self))

        if ttl:
            GObject.timeout_add(ttl * 1000, self.shutdown)

        self.__running = True
        self.__mainloop = GObject.MainLoop()
        context = self.__mainloop.get_context()
        try:
            while self.__running:
                if context.pending():
                    context.iteration(True)
                else:
                    time.sleep(0.01)
        except KeyboardInterrupt:
            pass
        self.zeroconf.close()
        logger.info('MDNSListener.run()') 
Example #6
Source File: listener.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def serve_forever(self, poll_interval=0.5):
        self.__running = False
        self.__mainloop = GObject.MainLoop()

        if hasattr(self, 'socket'):
            GObject.io_add_watch(
                self, GObject.IO_IN | GObject.IO_PRI, self._on_new_request)

        context = self.__mainloop.get_context()
        try:
            while not self.__running:
                if context.pending():
                    context.iteration(True)
                else:
                    time.sleep(0.01)
        except KeyboardInterrupt:
            pass
        logger.info('SSDPListener.serve_forever()') 
Example #7
Source File: gst-player.py    From streamlink with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self):
        self.fd = None
        self.mainloop = gobject.MainLoop()

        # This creates a playbin pipeline and using the appsrc source
        # we can feed it our stream data
        self.pipeline = gst.ElementFactory.make("playbin", None)
        self.pipeline.set_property("uri", "appsrc://")

        # When the playbin creates the appsrc source it will call
        # this callback and allow us to configure it
        self.pipeline.connect("source-setup", self.on_source_setup)

        # Creates a bus and set callbacks to receive errors
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect("message::eos", self.on_eos)
        self.bus.connect("message::error", self.on_error) 
Example #8
Source File: dirtyagent.py    From HomePWN with GNU General Public License v3.0 6 votes vote down vote up
def run_agent():
    if GObject:
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SystemBus()
        capability = "NoInputNoOutput"

        path = "/test/agent"
        agent = Agent(bus, path)

        mainloop = GObject.MainLoop()

        obj = bus.get_object(BUS_NAME, "/org/bluez")
        manager = dbus.Interface(obj, "org.bluez.AgentManager1")
        manager.RegisterAgent(path, capability)

        print("\n\n[+] Agent registered in background ")

        manager.RequestDefaultAgent(path)
        try:
            mainloop.run()
        except:
            print("\n[-] The agent has finished ")
    else:
        print("No agent running...") 
Example #9
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, device_id=None):
        """Default initialiser.

        1. Initialises the program loop using ``GObject``.
        2. Registers the Application on the D-Bus.
        3. Initialises the list of services offered by the application.

        """
        # Initialise the loop that the application runs in
        GObject.threads_init()
        dbus.mainloop.glib.threads_init()
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.mainloop = GObject.MainLoop()

        # Initialise the D-Bus path and register it
        self.bus = dbus.SystemBus()
        self.path = '/ukBaz/bluezero/application{}'.format(id(self))
        self.bus_name = dbus.service.BusName('ukBaz.bluezero', self.bus)
        dbus.service.Object.__init__(self, self.bus_name, self.path)

        # Initialise services within the application
        self.services = []

        self.dongle = adapter.Adapter(device_id) 
Example #10
Source File: decoder2_test.py    From kaldi-gstreamer-server with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setUpClass(cls):
            decoder_conf = {"model" : "test/models/estonian/nnet2_online_ivector/final.mdl",
                            "word-syms" : "test/models/estonian/nnet2_online_ivector/words.txt",
                            "fst" : "test/models/estonian/nnet2_online_ivector/HCLG.fst",
                            "mfcc-config" : "test/models/estonian/nnet2_online_ivector/conf/mfcc.conf",
                            "ivector-extraction-config": "test/models/estonian/nnet2_online_ivector/conf/ivector_extractor.conf",
                            "max-active": 7000,
                            "beam": 11.0,
                            "lattice-beam": 6.0,
                            "do-endpointing" : True,
                            "endpoint-silence-phones":"1:2:3:4:5:6:7:8:9:10"}
            cls.decoder_pipeline = DecoderPipeline2({"decoder" : decoder_conf})
            cls.final_hyps = []
            cls.finished = False

            cls.decoder_pipeline.set_result_handler(cls.result_getter)
            cls.decoder_pipeline.set_eos_handler(cls.set_finished, cls.finished)

            loop = GObject.MainLoop()
            thread.start_new_thread(loop.run, ()) 
Example #11
Source File: player.py    From gstreamer-python-player with MIT License 6 votes vote down vote up
def __init__(self):
        self.mainloop = GObject.MainLoop()
        #Creating the gst pipeline we're going to add elements to and use to play the file
        self.pipeline = Gst.Pipeline.new("mypipeline")

        #creating the filesrc element, and adding it to the pipeline
        self.filesrc = Gst.ElementFactory.make("filesrc", "filesrc")
        self.filesrc.set_property("location", """/path/to/mysoundfile.mp3""")
        self.pipeline.add(self.filesrc)
        
        #creating and adding the decodebin element , an "automagic" element able to configure itself to decode pretty much anything
        self.decode = Gst.ElementFactory.make("decodebin", "decode")
        self.pipeline.add(self.decode)
        #connecting the decoder's "pad-added" event to a handler: the decoder doesn't yet have an output pad (a source), it's created at runtime when the decoders starts receiving some data
        self.decode.connect("pad-added", self.decode_src_created) 
        
        #setting up (and adding) the alsasin, which is actually going to "play" the sound it receives
        self.sink = Gst.ElementFactory.make("alsasink", "sink")
        self.pipeline.add(self.sink)

        #linking elements one to another (here it's just the filesrc - > decoder link , the decoder -> sink link's going to be set up later)
        self.filesrc.link(self.decode)
            
    #handler taking care of linking the decoder's newly created source pad to the sink 
Example #12
Source File: support.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def install_gobject_iteration():
    '''Import and install gobject context iteration inside our event loop.
    This is used as soon as gobject is used (like gstreamer).
    '''

    from kivy.clock import Clock

    try:
        from gi.repository import GObject as gobject
    except ImportError:
        import gobject

    if hasattr(gobject, '_gobject_already_installed'):
        # already installed, don't do it twice.
        return

    gobject._gobject_already_installed = True

    # get gobject mainloop / context
    loop = gobject.MainLoop()
    gobject.threads_init()
    context = loop.get_context()

    # schedule the iteration each frame
    def _gobject_iteration(*largs):
        # XXX we need to loop over context here, otherwise, we might have a lag
        loop = 0
        while context.pending() and loop < 10:
            context.iteration(False)
            loop += 1
    Clock.schedule_interval(_gobject_iteration, 0)


# -----------------------------------------------------------------------------
# Android support
# ----------------------------------------------------------------------------- 
Example #13
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def startPipelineProcess(device, size, rotation, source, encoding, onListeningEvent, errorState, procPipe, debugLevel=0):
	from gi.repository import GObject

	GObject.threads_init()
	mainLoop = GObject.MainLoop()

	logger = logging.getLogger(__name__ + ':processLoop')
	interface = None

	def onFatalError(details):
		if interface:
			interface.sendResponse(0, {'error': 'fatal_error', 'details': details})
		else:
			#There was a fatal error during the creation of the pipeline, interface has not even been created
			logger.error('Fatal error creating pipeline: %s' % details)
			raise SystemExit(-1)

	try:
		pipeline = pipelineFactory(device, size, rotation, source, encoding, onFatalError, mainLoop, debugLevel)
	except InvalidGStreamerPipelineException as e:
		logger.error(e)
		raise SystemExit(-1)

	interface = processInterface(pipeline, procPipe, mainLoop, onListeningEvent)

	try:
		interface.start()
		logger.debug('Pipeline process started')
		mainLoop.run()

	except KeyboardInterrupt, SystemExit:
		mainLoop.quit() 
Example #14
Source File: async_tools.py    From python-bluezero with MIT License 5 votes vote down vote up
def __init__(self):
        self.mainloop = GObject.MainLoop() 
Example #15
Source File: audiotsmcli_gst.py    From audiotsm with MIT License 5 votes vote down vote up
def main():
    """Change the speed of an audio file without changing its pitch."""

    parser = argparse.ArgumentParser(description=(
        "Change the speed of an audio file without changing its pitch."))
    parser.add_argument(
        '-s', '--speed', metavar="S", type=float, default=1.,
        help="Set the speed ratio (e.g 0.5 to play at half speed)")
    parser.add_argument(
        'input_filename', metavar='INPUT_FILENAME', type=str,
        help="The audio input file")
    parser.add_argument(
        'output_filename', metavar='OUTPUT_FILENAME', type=str,
        help="The audio output file")

    args = parser.parse_args()

    if not os.path.isfile(args.input_filename):
        parser.error(
            'The input file "{}" does not exist.'.format(args.input_filename))

    pipeline = Pipeline()
    pipeline.set_speed(args.speed)
    pipeline.set_src_uri('file:///' + os.path.realpath(args.input_filename))
    pipeline.save(args.output_filename)

    loop = GObject.MainLoop()
    loop.run() 
Example #16
Source File: blueserver.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, tcp_port_in=8043, tcp_port_out=None, channel=1):
        self._spp = SerialPort(channel)
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        dbus.service.Object.__init__(
            self, dbus.SystemBus(), self._spp.profile_path)
        self.tcp_port_in = tcp_port_in
        self.tcp_port_out = tcp_port_out
        self._mainloop = GObject.MainLoop() 
Example #17
Source File: agent.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def __init__(
            self, client_class, timeout=180, capability="KeyboardDisplay",
            path="/org/bluez/my_bluetooth_agent"):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.client_class = client_class
        self.timeout = timeout
        self.capability = capability
        self.path = path
        self._bus = dbus.SystemBus()
        self._mainloop = GObject.MainLoop()
        _bluetooth.make_discoverable(False) 
Example #18
Source File: BlinkerBLE.py    From blinker-py with MIT License 5 votes vote down vote up
def mainInit():
    os.system('sudo service bluetooth stop')

    global mainloop

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    bus = dbus.SystemBus()

    service_manager = get_service_manager(bus)
    ad_manager = get_ad_manager(bus)

    app = BLEApplication(bus)

    # Create advertisement
    test_advertisement = BLEAdvertisement(bus, 0)

    mainloop = GObject.MainLoop()

    # Register gatt services
    service_manager.RegisterApplication(app.get_path(), {},
                                        reply_handler=register_app_cb,
                                        error_handler=register_app_error_cb)

    # Register advertisement
    ad_manager.RegisterAdvertisement(test_advertisement.get_path(), {},
                                     reply_handler=register_ad_cb,
                                     error_handler=register_ad_error_cb)

    try:
        mainloop.run()
    except KeyboardInterrupt:
        BLINKER_LOG ("exit")

# class BlinkerBLEService(Thread): 
Example #19
Source File: BlinkerBLE.py    From blinker-py with MIT License 5 votes vote down vote up
def __init__(self):
        # Thread.__init__(self)
        self._isClosed = False
        self.thread = None

        os.system('sudo service bluetooth stop')

        global mainloop

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        bus = dbus.SystemBus()

        service_manager = get_service_manager(bus)
        ad_manager = get_ad_manager(bus)

        app = BLEApplication(bus)

        # Create advertisement
        test_advertisement = BLEAdvertisement(bus, 0)

        mainloop = GObject.MainLoop()
        # mainloop = GLib.MainLoop()

        # Register gatt services
        service_manager.RegisterApplication(app.get_path(), {},
                                            reply_handler=register_app_cb,
                                            error_handler=register_app_error_cb)

        # Register advertisement
        ad_manager.RegisterAdvertisement(test_advertisement.get_path(), {},
                                        reply_handler=register_ad_cb,
                                        error_handler=register_ad_error_cb) 
Example #20
Source File: pyplot.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _backend_selection():
    """ If rcParams['backend_fallback'] is true, check to see if the
        current backend is compatible with the current running event
        loop, and if not switches to a compatible one.
    """
    backend = rcParams['backend']
    if not rcParams['backend_fallback'] or backend not in _interactive_bk:
        return
    is_agg_backend = rcParams['backend'].endswith('Agg')
    if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
        import wx
        if wx.App.IsMainLoopRunning():
            rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
    elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
        import PyQt4.QtGui
        if not PyQt4.QtGui.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt4Agg'
    elif 'PyQt5.QtCore' in sys.modules and not backend == 'Qt5Agg':
        import PyQt5.QtWidgets
        if not PyQt5.QtWidgets.qApp.startingUp():
            # The mainloop is running.
            rcParams['backend'] = 'qt5Agg'
    elif ('gtk' in sys.modules and
          backend not in ('GTK', 'GTKAgg', 'GTKCairo')):
        if 'gi' in sys.modules:
            from gi.repository import GObject
            ml = GObject.MainLoop
        else:
            import gobject
            ml = gobject.MainLoop
        if ml().is_running():
            rcParams['backend'] = 'gtk' + 'Agg' * is_agg_backend
    elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
        # import Tkinter
        pass  # what if anything do we need to do for tkinter? 
Example #21
Source File: support.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def install_gobject_iteration():
    '''Import and install gobject context iteration inside our event loop.
    This is used as soon as gobject is used (like gstreamer).
    '''

    from kivy.clock import Clock

    try:
        from gi.repository import GObject as gobject
    except ImportError:
        import gobject

    if hasattr(gobject, '_gobject_already_installed'):
        # already installed, don't do it twice.
        return

    gobject._gobject_already_installed = True

    # get gobject mainloop / context
    loop = gobject.MainLoop()
    gobject.threads_init()
    context = loop.get_context()

    # schedule the iteration each frame
    def _gobject_iteration(*largs):
        # XXX we need to loop over context here, otherwise, we might have a lag
        loop = 0
        while context.pending() and loop < 10:
            context.iteration(False)
            loop += 1
    Clock.schedule_interval(_gobject_iteration, 0)


# -----------------------------------------------------------------------------
# Android support
# ----------------------------------------------------------------------------- 
Example #22
Source File: service.py    From cputemp with MIT License 5 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.mainloop = GObject.MainLoop()
        self.bus = BleTools.get_bus()
        self.path = "/"
        self.services = []
        self.next_index = 0
        dbus.service.Object.__init__(self, self.bus, self.path) 
Example #23
Source File: gatt_linux.py    From gatt-python with MIT License 5 votes vote down vote up
def run(self):
        """
        Starts the main loop that is necessary to receive Bluetooth events from the Bluetooth adapter.

        This call blocks until you call `stop()` to stop the main loop.
        """

        if self._main_loop:
            return

        self._interface_added_signal = self._bus.add_signal_receiver(
            self._interfaces_added,
            dbus_interface='org.freedesktop.DBus.ObjectManager',
            signal_name='InterfacesAdded')

        # TODO: Also listen to 'interfaces removed' events?

        self._properties_changed_signal = self._bus.add_signal_receiver(
            self._properties_changed,
            dbus_interface=dbus.PROPERTIES_IFACE,
            signal_name='PropertiesChanged',
            arg0='org.bluez.Device1',
            path_keyword='path')

        def disconnect_signals():
            for device in self._devices.values():
                device.invalidate()
            self._properties_changed_signal.remove()
            self._interface_added_signal.remove()

        self._main_loop = GObject.MainLoop()
        try:
            self._main_loop.run()
            disconnect_signals()
        except Exception:
            disconnect_signals()
            raise 
Example #24
Source File: debian.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def run(self):
		self._stopped = False
		self._loop = GObject.MainLoop()

		self._propertiesListener = NetworkManager.NetworkManager.OnPropertiesChanged(self.propertiesChanged)
		self._stateChangeListener = NetworkManager.NetworkManager.OnStateChanged(self.globalStateChanged)

		connectionState = NetworkManager.NetworkManager.State
		logger.info('Network Manager reports state: *[%s]*' % NetworkManager.const('state', connectionState))
		if connectionState == NetworkManager.NM_STATE_CONNECTED_GLOBAL:
			self._setOnline(True)

		#d = self.getActiveConnectionDevice()
		#if d:
		#	self._devicePropertiesListener = d.Dhcp4Config.connect_to_signal('PropertiesChanged', self.activeDeviceConfigChanged)
		#	self._currentIpv4Address = d.Ip4Address
		#	self._activeDevice = d
		#	self._online = True
		#	logger.info('Active Connection found at %s (%s)' % (d.IpInterface, d.Ip4Address))

		while not self._stopped:
			try:
				self._loop.run()

			except KeyboardInterrupt:
				#kill the main process too
				from octoprint import astrobox
				astrobox.stop()

			except DBusException as e:
				#GObject.idle_add(logger.error, 'Exception during NetworkManagerEvents: %s' % e)
				logger.error('Exception during NetworkManagerEvents: %s' % e)

			finally:
				self.stop() 
Example #25
Source File: wifimonitor.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.bus = dbus.SystemBus()
        self._mainloop = GObject.MainLoop()

        self.wifi_manager = WiFiControl()

        self.callbacks = {}

        self.current_state = self.OFF_STATE
        self.current_ssid = None 
Example #26
Source File: provider.py    From Adafruit_Python_BluefruitLE with MIT License 5 votes vote down vote up
def run_mainloop_with(self, target):
        """Start the OS's main loop to process asyncronous BLE events and then
        run the specified target function in a background thread.  Target
        function should be a function that takes no parameters and optionally
        return an integer response code.  When the target function stops
        executing or returns with value then the main loop will be stopped and
        the program will exit with the returned code.

        Note that an OS main loop is required to process asyncronous BLE events
        and this function is provided as a convenience for writing simple tools
        and scripts that don't need to be full-blown GUI applications.  If you
        are writing a GUI application that has a main loop (a GTK glib main loop
        on Linux, or a Cocoa main loop on OSX) then you don't need to call this
        function.
        """
        # Spin up a background thread to run the target code.
        self._user_thread = threading.Thread(target=self._user_thread_main, args=(target,))
        self._user_thread.daemon = True  # Don't let the user thread block exit.
        self._user_thread.start()
        # Spin up a GLib main loop in the main thread to process async BLE events.
        self._gobject_mainloop = GObject.MainLoop()
        try:
            self._gobject_mainloop.run()  # Doesn't return until the mainloop ends.
        except KeyboardInterrupt:
            self._gobject_mainloop.quit()
            sys.exit(0)
        # Main loop finished.  Check if an exception occured and throw it,
        # otherwise return the status code from the user code.
        if self._exception is not None:
            # Rethrow exception with its original stack trace following advice from:
            # http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html
            raise_(self._exception[1], None, self._exception[2])
        else:
            sys.exit(self._return_code) 
Example #27
Source File: decoder_test.py    From kaldi-gstreamer-server with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUpClass(cls):
            decoder_conf = {"model" : "test/models/estonian/tri2b_mmi_pruned/final.mdl",
                            "lda-mat" : "test/models/estonian/tri2b_mmi_pruned/final.mat",
                            "word-syms" : "test/models/estonian/tri2b_mmi_pruned/words.txt",
                            "fst" : "test/models/estonian/tri2b_mmi_pruned/HCLG.fst",
                            "silence-phones" : "6"}
            cls.decoder_pipeline = DecoderPipeline({"decoder" : decoder_conf})
            cls.words = []
            cls.finished = False

            cls.decoder_pipeline.set_word_handler(cls.word_getter)
            cls.decoder_pipeline.set_eos_handler(cls.set_finished, cls.finished)

            loop = GObject.MainLoop()
            thread.start_new_thread(loop.run, ()) 
Example #28
Source File: session.py    From brave with Apache License 2.0 5 votes vote down vote up
def start(self):
        self._setup_initial_inputs_outputs_mixers_and_overlays()
        self.mainloop = GObject.MainLoop()
        GObject.timeout_add(PERIODIC_MESSAGE_FREQUENCY * 1000, self.periodic_message)
        self.mainloop.run()
        self.logger.debug('Mainloop has ended') 
Example #29
Source File: gstreamer.py    From python-snapcast with MIT License 5 votes vote down vote up
def __init__(self):
        """ Initialize app src. """
        self._mainloop = GObject.MainLoop()
        self._pipeline = Gst.Pipeline()

        # Make elements.
        self._src = Gst.ElementFactory.make('appsrc', 'appsrc')
        decode = Gst.ElementFactory.make("decodebin", "decode")
        self._queueaudio = Gst.ElementFactory.make('queue', 'queueaudio')
        audioconvert = Gst.ElementFactory.make('audioconvert', 'audioconvert')
        sink = Gst.ElementFactory.make('alsasink', 'sink')

        self._src.set_property('stream-type', 'stream')

        # Add to pipeline.
        self._pipeline.add(self._src)
        self._pipeline.add(decode)
        self._pipeline.add(self._queueaudio)
        self._pipeline.add(audioconvert)
        self._pipeline.add(sink)

        # Link elements.
        self._src.link(decode)
        self._queueaudio.link(audioconvert)
        audioconvert.link(sink)
        decode.connect('pad-added', self._decode_src_created) 
Example #30
Source File: pulseaudio.py    From pulseaudio-dlna with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        signal.signal(signal.SIGTERM, self.shutdown)
        if self.proc_title:
            setproctitle.setproctitle(self.proc_title)

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        signals = (
            ('NewPlaybackStream', 'org.PulseAudio.Core1.{}',
                self.on_new_playback_stream),
            ('PlaybackStreamRemoved', 'org.PulseAudio.Core1.{}',
                self.on_playback_stream_removed),
            ('FallbackSinkUpdated', 'org.PulseAudio.Core1.{}',
                self.on_fallback_sink_updated),
            ('DeviceUpdated', 'org.PulseAudio.Core1.Stream.{}',
                self.on_device_updated),
        )
        self._connect(signals)
        self.update()
        self.default_sink = self.fallback_sink

        self.thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)

        mainloop = GObject.MainLoop()
        GObject.io_add_watch(
            self.pulse_queue._reader, GObject.IO_IN | GObject.IO_PRI,
            self._on_new_message)
        try:
            mainloop.run()
        except KeyboardInterrupt:
            self.shutdown()