|
50 | 50 | import time |
51 | 51 | from os.path import abspath |
52 | 52 | from struct import pack, unpack |
53 | | -from subprocess import Popen |
| 53 | +from subprocess import Popen, check_output |
54 | 54 |
|
55 | 55 | try: |
56 | 56 | # This is a linux-specific module. |
@@ -3048,3 +3048,29 @@ def speak(text, espeak_opts='-a 200 -s 130'): |
3048 | 3048 | with open(os.devnull, 'w') as n: |
3049 | 3049 | cmd_line = '/usr/bin/espeak --stdout {0} "{1}" | /usr/bin/aplay -q'.format(espeak_opts, text) |
3050 | 3050 | return Popen(cmd_line, stdout=n, shell=True) |
| 3051 | + |
| 3052 | + @staticmethod |
| 3053 | + def set_volume(pct, channel=None): |
| 3054 | + """ |
| 3055 | + Sets the sound volume to the given percentage [0-100] by calling |
| 3056 | + ``amixer -q set <channel> <pct>%``. |
| 3057 | + If the channel is not specified, it tries to determine the default one |
| 3058 | + by running ``amixer scontrols``. If that fails as well, it uses the |
| 3059 | + ``Playback`` channel, as that is the only channel on the EV3. |
| 3060 | + """ |
| 3061 | + if channel is None: |
| 3062 | + # Get default channel as the first one that pops up in |
| 3063 | + # 'amixer scontrols' output, which contains strings in the |
| 3064 | + # following format: |
| 3065 | + # |
| 3066 | + # Simple mixer control 'Master',0 |
| 3067 | + # Simple mixer control 'Capture',0 |
| 3068 | + out = check_output(['amixer', 'scontrols']).decode() |
| 3069 | + m = re.search("'(?P<channel>[^']+)'", out) |
| 3070 | + if m: |
| 3071 | + channel = m.group('channel') |
| 3072 | + else: |
| 3073 | + channel = 'Playback' |
| 3074 | + |
| 3075 | + cmd_line = '/usr/bin/amixer -q set {0} {1:d}%'.format(channel, pct) |
| 3076 | + Popen(cmd_line, shell=True).wait() |
0 commit comments