Skip to content

Commit 04681c9

Browse files
authored
Provide Sound.set_volume(pct) (#259)
Closes #258
1 parent ef6c6ea commit 04681c9

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

ev3dev/core.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
import time
5151
from os.path import abspath
5252
from struct import pack, unpack
53-
from subprocess import Popen
53+
from subprocess import Popen, check_output
5454

5555
try:
5656
# This is a linux-specific module.
@@ -3048,3 +3048,29 @@ def speak(text, espeak_opts='-a 200 -s 130'):
30483048
with open(os.devnull, 'w') as n:
30493049
cmd_line = '/usr/bin/espeak --stdout {0} "{1}" | /usr/bin/aplay -q'.format(espeak_opts, text)
30503050
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

Comments
 (0)