File: audiopy

package info (click to toggle)
python2.4 2.4.6-1%2Blenny1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 44,888 kB
  • ctags: 86,995
  • sloc: ansic: 306,391; python: 271,931; sh: 10,210; makefile: 4,248; perl: 3,736; lisp: 3,678; xml: 894; objc: 756; cpp: 7; sed: 2
file content (507 lines) | stat: -rwxr-xr-x 16,660 bytes parent folder | download | duplicates (21)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#! /usr/bin/env python

"""audiopy -- a program to control the Solaris audio device.

Contact: Barry Warsaw
Email:   bwarsaw@python.org
Version: %(__version__)s

When no arguments are given, this pops up a graphical window which lets you
choose the audio input and output devices, and set the output volume.

This program can be driven via the command line, and when done so, no window
pops up.  Most options have the general form:

    --device[={0,1}]
    -d[={0,1}]
        Set the I/O device.  With no value, it toggles the specified device.
        With a value, 0 turns the device off and 1 turns the device on.

The list of devices and their short options are:

 (input)
    microphone  -- m
    linein      -- i
    cd          -- c

 (output)
    headphones  -- p
    speaker     -- s
    lineout     -- o

Other options are:

    --gain volume
    -g volume
        Sets the output gain to the specified volume, which must be an integer
        in the range [%(MIN_GAIN)s..%(MAX_GAIN)s]

    --version
    -v
        Print the version number and exit.

    --help
    -h
        Print this message and exit.
"""

import sys
import os
import errno
import sunaudiodev
from SUNAUDIODEV import *

# Milliseconds between interrupt checks
KEEPALIVE_TIMER = 500

__version__ = '1.1'



class MainWindow:
    def __init__(self, device):
        from Tkinter import *
        self.__helpwin = None
        self.__devctl = device
        info = device.getinfo()
        #
        self.__tkroot = tkroot = Tk(className='Audiopy')
        tkroot.withdraw()
        # create the menubar
        menubar = Menu(tkroot)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Quit',
                             command=self.__quit,
                             accelerator='Alt-Q',
                             underline=0)
        helpmenu = Menu(menubar, name='help', tearoff=0)
        helpmenu.add_command(label='About Audiopy...',
                             command=self.__popup_about,
                             underline=0)
        helpmenu.add_command(label='Help...',
                             command=self.__popup_using,
                             underline=0)
        menubar.add_cascade(label='File',
                            menu=filemenu,
                            underline=0)
        menubar.add_cascade(label='Help',
                            menu=helpmenu,
                            underline=0)
        # now create the top level window
        root = self.__root = Toplevel(tkroot, class_='Audiopy', menu=menubar)
        root.protocol('WM_DELETE_WINDOW', self.__quit)
        root.title('audiopy ' + __version__)
        root.iconname('audiopy ' + __version__)
        root.tk.createtimerhandler(KEEPALIVE_TIMER, self.__keepalive)
        #
        buttons = []
        #
        # where does input come from?
        frame = Frame(root, bd=1, relief=RAISED)
        frame.grid(row=1, column=0, sticky='NSEW')
        label = Label(frame, text='Input From:')
        label.grid(row=0, column=0, sticky=E)
        self.__inputvar = IntVar()
        ##
        btn = Radiobutton(frame,
                          text='None',
                          variable=self.__inputvar,
                          value=0,
                          command=self.__pushtodev,
                          underline=0)
        btn.grid(row=0, column=1, sticky=W)
        root.bind('<Alt-n>', self.__none)
        root.bind('<Alt-N>', self.__none)
        if not info.i_avail_ports & MICROPHONE:
            btn.configure(state=DISABLED)
        buttons.append(btn)
        ##
        btn = Radiobutton(frame,
                          text='Microphone',
                          variable=self.__inputvar,
                          value=MICROPHONE,
                          command=self.__pushtodev,
                          underline=0)
        btn.grid(row=1, column=1, sticky=W)
        root.bind('<Alt-m>', self.__mic)
        root.bind('<Alt-M>', self.__mic)
        if not info.i_avail_ports & MICROPHONE:
            btn.configure(state=DISABLED)
        buttons.append(btn)
        ##
        btn = Radiobutton(frame,
                          text='Line In',
                          variable=self.__inputvar,
                          value=LINE_IN,
                          command=self.__pushtodev,
                          underline=5)
        btn.grid(row=2, column=1, sticky=W)
        root.bind('<Alt-i>', self.__linein)
        root.bind('<Alt-I>', self.__linein)
        if not info.i_avail_ports & LINE_IN:
            btn.configure(state=DISABLED)
        buttons.append(btn)
        ## if SUNAUDIODEV was built on an older version of Solaris, the CD
        ## input device won't exist
        try:
            btn = Radiobutton(frame,
                              text='CD',
                              variable=self.__inputvar,
                              value=CD,
                              command=self.__pushtodev,
                              underline=0)
            btn.grid(row=3, column=1, sticky=W)
            root.bind('<Alt-c>', self.__cd)
            root.bind('<Alt-C>', self.__cd)
            if not info.i_avail_ports & CD:
                btn.configure(state=DISABLED)
            buttons.append(btn)
        except NameError:
            pass
        #
        # where does output go to?
        frame = Frame(root, bd=1, relief=RAISED)
        frame.grid(row=2, column=0, sticky='NSEW')
        label = Label(frame, text='Output To:')
        label.grid(row=0, column=0, sticky=E)
        self.__spkvar = IntVar()
        btn = Checkbutton(frame,
                          text='Speaker',
                          variable=self.__spkvar,
                          onvalue=SPEAKER,
                          command=self.__pushtodev,
                          underline=0)
        btn.grid(row=0, column=1, sticky=W)
        root.bind('<Alt-s>', self.__speaker)
        root.bind('<Alt-S>', self.__speaker)
        if not info.o_avail_ports & SPEAKER:
            btn.configure(state=DISABLED)
        buttons.append(btn)
        ##
        self.__headvar = IntVar()
        btn = Checkbutton(frame,
                          text='Headphones',
                          variable=self.__headvar,
                          onvalue=HEADPHONE,
                          command=self.__pushtodev,
                          underline=4)
        btn.grid(row=1, column=1, sticky=W)
        root.bind('<Alt-p>', self.__headphones)
        root.bind('<Alt-P>', self.__headphones)
        if not info.o_avail_ports & HEADPHONE:
            btn.configure(state=DISABLED)
        buttons.append(btn)
        ##
        self.__linevar = IntVar()
        btn = Checkbutton(frame,
                          variable=self.__linevar,
                          onvalue=LINE_OUT,
                          text='Line Out',
                          command=self.__pushtodev,
                          underline=0)
        btn.grid(row=2, column=1, sticky=W)
        root.bind('<Alt-l>', self.__lineout)
        root.bind('<Alt-L>', self.__lineout)
        if not info.o_avail_ports & LINE_OUT:
            btn.configure(state=DISABLED)
        buttons.append(btn)
        #
        # Fix up widths
        widest = 0
        for b in buttons:
            width = b['width']
            if width > widest:
                widest = width
        for b in buttons:
            b.configure(width=widest)
        # root bindings
        root.bind('<Alt-q>', self.__quit)
        root.bind('<Alt-Q>', self.__quit)
        #
        # Volume
        frame = Frame(root, bd=1, relief=RAISED)
        frame.grid(row=3, column=0, sticky='NSEW')
        label = Label(frame, text='Output Volume:')
        label.grid(row=0, column=0, sticky=W)
        self.__scalevar = IntVar()
        self.__scale = Scale(frame,
                             orient=HORIZONTAL,
                             from_=MIN_GAIN,
                             to=MAX_GAIN,
                             length=200,
                             variable=self.__scalevar,
                             command=self.__volume)
        self.__scale.grid(row=1, column=0, sticky=EW)
        #
        # do we need to poll for changes?
        self.__needtopoll = 1
        try:
            fd = self.__devctl.fileno()
            self.__needtopoll = 0
        except AttributeError:
            pass
        else:
            import fcntl
            import signal
            import STROPTS
            # set up the signal handler
            signal.signal(signal.SIGPOLL, self.__update)
            fcntl.ioctl(fd, STROPTS.I_SETSIG, STROPTS.S_MSG)
            self.__update()
        
    def __quit(self, event=None):
        self.__devctl.close()
        self.__root.quit()

    def __popup_about(self, event=None):
        import tkMessageBox
        tkMessageBox.showinfo('About Audiopy ' + __version__,
                              '''\
Audiopy %s
Control the Solaris audio device

For information
Contact: Barry A. Warsaw
Email:   bwarsaw@python.org''' % __version__)

    def __popup_using(self, event=None):
        if not self.__helpwin:
            self.__helpwin = Helpwin(self.__tkroot, self.__quit)
        self.__helpwin.deiconify()
            

    def __keepalive(self):
        # Exercise the Python interpreter regularly so keyboard interrupts get
        # through.
        self.__tkroot.tk.createtimerhandler(KEEPALIVE_TIMER, self.__keepalive)
        if self.__needtopoll:
            self.__update()

    def __update(self, num=None, frame=None):
        # It's possible (although I have never seen it) to get an interrupted
        # system call during the getinfo() call.  If so, and we're polling,
        # don't sweat it because we'll come around again later.  Otherwise,
        # we'll give it a couple of tries and then give up until next time.
        tries = 0
        while 1:
            try:
                info = self.__devctl.getinfo()
                break
            except sunaudiodev.error:
                if self.__needtopoll or tries > 3:
                    return
                tries = tries + 1
        # input
        self.__inputvar.set(info.i_port)
        # output
        self.__spkvar.set(info.o_port & SPEAKER)
        self.__headvar.set(info.o_port & HEADPHONE)
        self.__linevar.set(info.o_port & LINE_OUT)
        # volume
        self.__scalevar.set(info.o_gain)

    def __pushtodev(self, event=None):
        info = self.__devctl.getinfo()
        info.o_port = self.__spkvar.get() + \
                      self.__headvar.get() + \
                      self.__linevar.get()
        info.i_port = self.__inputvar.get()
        info.o_gain = self.__scalevar.get()
        try:
            self.__devctl.setinfo(info)
        except sunaudiodev.error, msg:
            # TBD: what to do?  it's probably temporary.
            pass

    def __getset(self, var, onvalue):
        if var.get() == onvalue:
            var.set(0)
        else:
            var.set(onvalue)
        self.__pushtodev()

    def __none(self, event=None):
        self.__inputvar.set(0)
        self.__pushtodev()

    def __mic(self, event=None):
        self.__getset(self.__inputvar, MICROPHONE)

    def __linein(self, event=None):
        self.__getset(self.__inputvar, LINE_IN)

    def __cd(self, event=None):
        self.__getset(self.__inputvar, CD)

    def __speaker(self, event=None):
        self.__getset(self.__spkvar, SPEAKER)

    def __headphones(self, event=None):
        self.__getset(self.__headvar, HEADPHONE)

    def __lineout(self, event=None):
        self.__getset(self.__linevar, LINE_OUT)

    def __volume(self, event=None):
        self.__pushtodev()

    def start(self):
        self.__keepalive()
        self.__tkroot.mainloop()



class Helpwin:
    def __init__(self, master, quitfunc):
        from Tkinter import *
        self.__root = root = Toplevel(master, class_='Audiopy')
        root.protocol('WM_DELETE_WINDOW', self.__withdraw)
        root.title('Audiopy Help Window')
        root.iconname('Audiopy Help Window')
        root.bind('<Alt-q>', quitfunc)
        root.bind('<Alt-Q>', quitfunc)
        root.bind('<Alt-w>', self.__withdraw)
        root.bind('<Alt-W>', self.__withdraw)

        # more elaborate help is available in the README file
        readmefile = os.path.join(sys.path[0], 'README')
        try:
            fp = None
            try:
                fp = open(readmefile)
                contents = fp.read()
                # wax the last page, it contains Emacs cruft
                i = contents.rfind('\f')
                if i > 0:
                    contents = contents[:i].rstrip()
            finally:
                if fp:
                    fp.close()
        except IOError:
            sys.stderr.write("Couldn't open audiopy's README, "
                             'using docstring instead.\n')
            contents = __doc__ % globals()

        self.__text = text = Text(root, relief=SUNKEN,
                                  width=80, height=24)
        text.insert(0.0, contents)
        scrollbar = Scrollbar(root)
        scrollbar.pack(fill=Y, side=RIGHT)
        text.pack(fill=BOTH, expand=YES)
        text.configure(yscrollcommand=(scrollbar, 'set'))
        scrollbar.configure(command=(text, 'yview'))

    def __withdraw(self, event=None):
        self.__root.withdraw()

    def deiconify(self):
        self.__root.deiconify()




def usage(code, msg=''):
    print __doc__ % globals()
    if msg:
        print msg
    sys.exit(code)


def main():
    #
    # Open up the audio control device and query for the current output
    # device
    device = sunaudiodev.open('control')

    if len(sys.argv) == 1:
        # GUI
        w = MainWindow(device)
        try:
            w.start()
        except KeyboardInterrupt:
            pass
        return

    # spec:    LONG OPT, SHORT OPT, 0=input,1=output, MASK
    options = [('--microphone', '-m', 0, MICROPHONE),
               ('--linein',     '-i', 0, LINE_IN),
               ('--headphones', '-p', 1, HEADPHONE),
               ('--speaker',    '-s', 1, SPEAKER),
               ('--lineout',    '-o', 1, LINE_OUT),
               ]
    # See the comment above about `CD'
    try:
        options.append(('--cd',         '-c', 0, CD))
    except NameError:
        pass

    info = device.getinfo()
    # first get the existing values
    i = 0
    while i < len(sys.argv)-1:
        i = i + 1
        arg = sys.argv[i]
        if arg in ('-h', '--help'):
            usage(0)
            # does not return
        elif arg in ('-g', '--gain'):
            gainspec = '<missing>'
            try:
                gainspec = sys.argv[i+1]
                gain = int(gainspec)
            except (ValueError, IndexError):
                usage(1, 'Bad gain specification: ' + gainspec)
            info.o_gain = gain
            i = i + 1
            continue
        elif arg in ('-v', '--version'):
            print '''\
audiopy -- a program to control the Solaris audio device.
Contact: Barry Warsaw
Email:   bwarsaw@python.org
Version: %s''' % __version__            
            sys.exit(0)
        for long, short, io, mask in options:
            if arg in (long, short):
                # toggle the option
                if io == 0: 
                    info.i_port = info.i_port ^ mask
                else:
                    info.o_port = info.o_port ^ mask
                break
            val = None
            try:
                if arg[:len(long)+1] == long+'=':
                    val = int(arg[len(long)+1:])
                elif arg[:len(short)+1] == short+'=':
                    val = int(arg[len(short)+1:])
            except ValueError:
                usage(1, msg='Invalid option: ' + arg)
                # does not return
            if val == 0:
                if io == 0:
                    info.i_port = info.i_port & ~mask
                else:
                    info.o_port = info.o_port & ~mask
                break
            elif val == 1:
                if io == 0:
                    info.i_port = info.i_port | mask
                else:
                    info.o_port = info.o_port | mask
                break
            # else keep trying next option
        else:
            usage(1, msg='Invalid option: ' + arg)
    # now set the values
    try:
        device.setinfo(info)
    except sunaudiodev.error, (code, msg):
        if code <> errno.EINVAL:
            raise
    device.close()
            


if __name__ == '__main__':
    main()