Project

General

Profile

Statistics
| Branch: | Revision:

gdp-if / audio / playback.py @ master

History | View | Annotate | Download (1.87 KB)

1 44e6359c Nitesh Mor
#!/usr/bin/env python
2
3
""" Subscribe to a log and play audio data """
4
5
import gdp
6
import sys
7
import time
8
import json
9
import pyaudio
10
from threading import Lock
11
12
13
DELAY_RECS = 5
14
15
16
pcm_buf = ""
17
channels = None
18
sampleWidth = None
19
samplingRate = None
20
21
22
def playAudio(lh):
23
24
    print ">>>", "sampleWidth:", sampleWidth, "channels:", channels,
25
    print "samplingRate:", samplingRate
26
27
    def __helperCallback(in_data, frame_count, time_info, status):
28
        global pcm_buf
29
        ret_len = frame_count*channels*sampleWidth
30
        while len(pcm_buf)<ret_len:
31
            time.sleep(0.01)
32
        pcm_buf_lock.acquire()
33
        out_data = pcm_buf[:ret_len]
34
        pcm_buf = pcm_buf[ret_len:]
35
        pcm_buf_lock.release()
36
        return (out_data, pyaudio.paContinue)
37
38
    p = pyaudio.PyAudio()
39
    stream = p.open(format=p.get_format_from_width(sampleWidth),
40
                    channels=channels, rate=samplingRate,
41
                    input=False, output=True, stream_callback=__helperCallback)
42
43
    global pcm_buf
44
    pcm_buf_lock = Lock()
45
    # subscribe to the log
46
    lh.subscribe(-DELAY_RECS, 0, None)
47
    stream.start_stream()
48
    
49
    while True:
50
        event = gdp.GDP_GCL.get_next_event(None)
51
        pcm_buf_lock.acquire()
52
        pcm_buf += event['datum']['data']
53
        pcm_buf_lock.release()
54
    
55
    stream.stop_stream()
56
    stream.close()
57
    p.terminate()
58
    
59
60
def main(logname):
61
62
    gdp.gdp_init()
63
    lh = gdp.GDP_GCL(gdp.GDP_NAME(logname), gdp.GDP_MODE_RO)
64
65
    firstRecord = lh.read(1)
66
    audioParams = json.loads(firstRecord['data'])
67
    global sampleWidth
68
    global samplingRate
69
    global channels
70
    sampleWidth = audioParams['sampleWidth']
71
    samplingRate = audioParams['samplingRate']
72
    channels = audioParams['channels']
73
74
    playAudio(lh)
75
76
77
if __name__=="__main__":
78
    if len(sys.argv)<2:
79
        print "Usage: %s logname" % sys.argv[0]
80
        sys.exit(1)
81
82
    main(sys.argv[1])