Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/Speak.activity/audio.py
blob: 484285dca5df0e256f113360924625395defd110 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import pygst
pygst.require("0.10")
import gst
import pygtk
import gtk, gobject
import signal, os
import time
import dbus
import audioop
from struct import *

class AudioGrab(gobject.GObject):
    __gsignals__ = {
        'new-buffer': (gobject.SIGNAL_RUN_FIRST, None, [gobject.TYPE_PYOBJECT])
    }

    def __init__(self, datastore, _jobject):
        gobject.GObject.__init__(self)
        self.pipeline = None

    def playfile(self, filename):
        # build a pipeline that reads the given file
        # and sends it to both the real audio output
        # and a fake one that we use to draw from
        p = 'filesrc name=file-source ! decodebin ! tee name=tee tee.! audioconvert ! alsasink tee.! queue ! audioconvert name=conv'
        self.pipeline = gst.parse_launch(p)
        
        # make a fakesink to capture audio
        fakesink = gst.element_factory_make("fakesink", "fakesink")
        fakesink.connect("handoff",self.on_buffer)
        fakesink.set_property("signal-handoffs",True)
        self.pipeline.add(fakesink)

        # attach it to the pipeline
        conv = self.pipeline.get_by_name("conv")
        gst.element_link_many(conv, fakesink)
        
        # set the source file
        self.pipeline.get_by_name("file-source").set_property('location', filename)
        
        # play
        self.restart_sound_device()
        
        # how do we detect when the sample has finished playing?
        # we should stop the sound device and stop emitting buffers
        # to save on CPU and battery usage when there is no audio playing
        
    def on_quit(self):
        self.pipeline.set_state(gst.STATE_NULL)

    def _new_buffer(self, buf):
        # pass captured audio to anyone who is interested via the main thread
        self.emit("new-buffer", buf)
        return False

    def on_buffer(self,element,buffer,pad):
        # we got a new buffer of data, ask for another
        gobject.timeout_add(100, self._new_buffer, str(buffer))
        return True

    def stop_sound_device(self):
        self.pipeline.set_state(gst.STATE_NULL)

    def restart_sound_device(self):
        self.pipeline.set_state(gst.STATE_PLAYING)