forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpisoothe
More file actions
executable file
·373 lines (330 loc) · 12.5 KB
/
pisoothe
File metadata and controls
executable file
·373 lines (330 loc) · 12.5 KB
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
#!/usr/bin/env python
# pisooth: play soothing noise files (rain, water etc.) in a loop,
# while scanning for user input to control skipping to the next
# file, shutting down or other options.
#
# Copyright 2012 by Akkana Peck, http://shallowsky.com.
# Share and enjoy under the GPLv2 or (at your option) any later version.
#
# It's called pisoothe because it's intended as a script that will
# turn a Raspberry Pi into a sleep soother machine you can take with
# you on trips.
# To use this on as the sole program on a Raspberry Pi (q will shut down),
# add the following to the end of /etc/rc.local:
#
# /path/to/pisoothe file1.wav file2.wav ...
# /sbin/poweroff
#
# Take input from a keyboard if there is one, or mouse if we're not in X,
# for volume, changing track, and shutdown.
# http://pythonhosted.org/evdev/
import sys, os
import subprocess
import time # for sleep()
import termios, fcntl # For non-blocking key reads
import alsaaudio
try:
import evdev
import select
use_mouse = True
except:
use_mouse = False
class SoundPlayer :
"""
Asynchronously play sounds that don't overlap in time.
Allow for querying whether a sound is still playing,
or killing it to start a new sound.
"""
PLAYER = "/usr/bin/aplay"
def __init__(self, file_list, debug=False) :
self.curpath = None
self.current = None
self.file_list = file_list
self.samplenum = 0
self.retcode = -1
self.debug = debug
self.vol_increment = 4
try:
self.mixer = alsaaudio.Mixer('Master', 0)
except alsaaudio.ALSAAudioError:
try:
self.mixer = alsaaudio.Mixer('PCM', 0)
except alsaaudio.ALSAAudioError:
sys.stderr.write("No such mixer\n")
self.mixer = None
def __del__(self) :
self.kill()
def kill(self) :
if self.current :
if self.debug :
print "Killing"
self.current.kill() # or try terminate()
elif self.debug : print "Already dead, no need to kill"
def skip_track(self, direction):
print "Next sound"
self.samplenum += direction
if self.samplenum < 0:
self.samplenum = len(self.file_list) - 1
elif self.samplenum >= len(self.file_list):
self.samplenum = 0
self.play(True)
def change_volume(self, direction):
if not self.mixer:
print "Can't change volume -- no mixer"
return
if direction == 0:
return
if self.debug:
if direction > 0:
print "Louder"
else:
print "Quieter"
cur = self.mixer.getvolume()[0]
cur += self.vol_increment * direction
if cur > 100:
cur = 100
if cur < 0:
cur = 0
self.mixer.setvolume(cur, alsaaudio.MIXER_CHANNEL_ALL)
if self.debug:
print "Set volume to", cur
def play(self, interrupt=False) :
path = self.file_list[self.samplenum]
if self.current :
if self.current.poll() is None :
# Current process hasn't finished yet. Is this the same sound?
if path == self.curpath :
# A repeat of the currently playing sound.
# Don't play it more than once.
if self.debug :
print path, "is still playing. Not playing again"
return
elif interrupt :
# Stop the currently playing process,
# so we can play a new one.
self.kill()
if self.debug :
print "Waiting for process to die:",
while self.current.poll() == None :
time.sleep(.2)
if self.debug :
print ".",
if self.debug :
print "Gone."
else :
# Trying to play a different sound.
# Wait on the current sound then play the new one.
if self.debug :
print "Different sound; first waiting for", self.curpath
self.wait()
self.current = None
self.curpath = None
if self.debug :
print "Playing", path
self.curpath = path
self.current = subprocess.Popen([ SoundPlayer.PLAYER, '-q', path ] )
def poll(self) :
'''Returns None if currently playing, else last exit code.'''
if not self.current :
return self.retcode
poll = self.current.poll()
if poll != None :
self.retcode = self.current.returncode
self.current = None
self.curpath = None
return poll
def is_done(self) :
'''Simpler version of retcode: returns True if the process is
finished, False otherwise.
'''
if not self.current :
return True
if self.poll() != None :
return True
return False
def wait(self) :
if self.current and self.current.poll() == None :
self.current.wait()
class KeyReader :
'''
Read keypresses one at a time, without waiting for a newline.
Uses the technique from
http://docs.python.org/2/faq/library.html#how-do-i-get-a-single-keypress-at-a-time
'''
def __init__(self, echo=False) :
'''Put the terminal into cbreak and noecho mode.'''
self.fd = sys.stdin.fileno()
self.oldterm = termios.tcgetattr(self.fd)
newattr = termios.tcgetattr(self.fd)
newattr[3] = newattr[3] & ~termios.ICANON
if not echo :
newattr[3] = newattr[3] & ~termios.ECHO
termios.tcsetattr(self.fd, termios.TCSANOW, newattr)
self.oldflags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK)
# Sad hack: when the destructor __del__ is called,
# the fcntl module may already be unloaded, so we can no longer
# call fcntl.fcntl() to set the terminal back to normal.
# So just in case, store a reference to the fcntl module,
# and also to termios (though I haven't yet seen a case
# where termios was gone -- for some reason it's just fnctl).
# The idea of keeping references to the modules comes from
# http://bugs.python.org/issue5099
# though I don't know if it'll solve the problem completely.
self.fcntl = fcntl
self.termios = termios
def __del__(self) :
'''Reset the terminal before exiting the program.'''
self.termios.tcsetattr(self.fd, self.termios.TCSAFLUSH, self.oldterm)
self.fcntl.fcntl(self.fd, self.fcntl.F_SETFL, self.oldflags)
def getch(self) :
'''Read keyboard input, returning a string.
Note that one key may result in a string of more than one character,
e.g. arrow keys that send escape sequences.
There may also be multiple keystrokes queued up since the last read.
This function, sadly, cannot read special characters like VolumeUp.
They don't show up in ordinary CLI reads -- you have to be in
a window system like X to get those special keycodes.
'''
try:
return sys.stdin.read()
except IOError:
return None
class MouseReader:
def __init__(self):
self.mousedevice = None
devices = map(evdev.InputDevice, evdev.list_devices())
for dev in devices:
caps = dev.capabilities()
keys = caps.keys()
# 1L is "EV_KEY" events (mouse buttons);
# 2L is 'EV_REL' for the wheel.
if evdev.ecodes.EV_KEY in keys and evdev.ecodes.EV_REL in keys:
if evdev.ecodes.BTN_LEFT in caps[evdev.ecodes.EV_KEY] and \
evdev.ecodes.BTN_RIGHT in caps[evdev.ecodes.EV_KEY] \
and evdev.ecodes.REL_WHEEL in caps[evdev.ecodes.EV_REL]:
# Quacks like a mouse. Use it.
self.mousedevice = dev
return
if not mousedevice:
print "Didn't see a mouse device"
def pval(self, code, val):
try:
codes = evdev.ecodes.BTN[code]
if type(codes) is list:
print codes[0],
else:
print codes,
except:
try:
print evdev.ecodes.REL[code],
except:
print "Unknown code", code
if val == 1:
if code == evdev.ecodes.REL_WHEEL:
print "scroll up"
else:
print "press"
elif val == 0:
print "release"
elif val == -1:
print "scroll down"
else:
print "unknown value", val
def read_mouse(self, timeout=None):
'''Returns an evdev event.
timeout is specified in floating-point seconds.
timeout=None will block until there's something to read.
'''
r,w,x = select.select([self.mousedevice], [], [], timeout)
if not r:
return []
events = []
for event in self.mousedevice.read():
# Only return codes for main three buttons plus wheel.
if event.code in (evdev.ecodes.REL_WHEEL,
evdev.ecodes.BTN_LEFT,
evdev.ecodes.BTN_RIGHT,
evdev.ecodes.BTN_MIDDLE):
events.append((event.code, event.value))
return events
# main
# Pass sound files as arguments.
# pisoothe ambient_rain.wav caribbeanbeach_near.wav storm_water_2.wav
if __name__ == "__main__" :
if len(sys.argv) < 1 :
print "Usage: %s soundfile soundfile soundfile ..." % sys.argv[0]
sys.exit(1)
# Use input from a mouse if we're reading one:
if use_mouse:
try:
mousereader = MouseReader()
if not mousereader.mousedevice:
mousereader = None
except:
mousereader = None
else:
mousereader = None
try:
readkey = KeyReader()
except:
readkey = None
player = SoundPlayer(sys.argv[1:], debug=True)
player.play()
while True :
time.sleep(1)
if mousereader:
events = mousereader.read_mouse(0)
# First look for a left and right pressed at the same time.
# That will be a signal to exit or maybe power down
# the computer.
if (evdev.ecodes.BTN_LEFT, 1) in events and \
(evdev.ecodes.BTN_RIGHT, 1) in events:
print "Yowee! Right and left buttons pressed at once!"
# On most systems. use sys.exit. On the RPi, shut down.
if os.path.exists("/etc/rpi-issue"):
print "We're on a Raspberry Pi -- shutting down!"
os.system("/sbin/poweroff")
sys.exit(0)
print "(not a Raspberry Pi)"
sys.exit(0)
for ev in events:
if ev[0] == evdev.ecodes.BTN_RIGHT and ev[1] == 1:
player.skip_track(1)
continue
if ev[0] == evdev.ecodes.BTN_LEFT and ev[1] == 1:
player.skip_track(-1)
continue
if ev[0] == evdev.ecodes.REL_WHEEL:
player.change_volume(ev[1])
if readkey:
c = readkey.getch()
else:
c = None
if not c : # Didn't read anything. Is the current sound still playing?
if player.is_done() :
player.play()
continue
# Else we did read a character. Act on it:
if c == 'q' :
# print "Bye!"
sys.exit(0)
if c == 'n' :
player.skip_track(1)
continue
if c == 'p' :
player.skip_track(-1)
continue
if c == '\x1b[A' : # Up arrow
player.change_volume(1)
continue
if c == '\x1b[B' : # Down arrow
player.change_volume(-1)
continue
# If we get here, it was an unrecognized character.
print "Don't know key",
for cc in c :
o = ord(cc)
if o < 32 : cc = ' ' # Don't try to print nonprintables
print '%c (%d)' % (cc, o),
print