tar*_*110 6 python pulseaudio alsa 14.04 amixer
我可以通过终端使用此命令控制音量amixer -D pulse sset Master 0%
。我的问题是如何使用 python 脚本做同样的事情。
Tim*_*Tim 11
您可以call
从subprocess
模块中使用:
from subprocess import call
call(["amixer", "-D", "pulse", "sset", "Master", "0%"])
Run Code Online (Sandbox Code Playgroud)
当然,你可以使用普通的 python 代码:
valid = False
while not valid:
volume = input('What volume? > ')
try:
volume = int(volume)
if (volume <= 100) and (volume >= 0):
call(["amixer", "-D", "pulse", "sset", "Master", str(volume)+"%"])
valid = True
except ValueError:
pass
Run Code Online (Sandbox Code Playgroud)
此代码将循环直到用户给出有效输入 - 0 到 100 之间,然后将音量设置为该值。
这将在Python 3.更改运行input
到raw_input
Python的2。
要在脚本运行时增加 10%,您可以执行以下两项操作之一。
您可以使用该alsaaudio
模块。
首先,安装
sudo apt-get install python-alsaaudio
Run Code Online (Sandbox Code Playgroud)
然后导入它:
import alsaaudio
Run Code Online (Sandbox Code Playgroud)
我们可以得到音量:
>>> m = alsaaudio.Mixer()
>>> vol = m.getvolume()
>>> vol
[50L]
Run Code Online (Sandbox Code Playgroud)
我们还可以设置音量:
>>> m.setvolume(20)
>>> vol = m.getvolume()
>>> vol
[20L]
Run Code Online (Sandbox Code Playgroud)
此数字是列表中的长整数。所以为了使它成为一个可用的数字,我们可以做int(vol[0])
.
那么运行时要增加10%呢?
import alsaaudio
m = alsaaudio.Mixer()
vol = m.getvolume()
vol = int(vol[0])
newVol = vol + 10
m.setvolume(newVol)
Run Code Online (Sandbox Code Playgroud)
或者我们可以坚持使用subprocess
模块和默认的 Ubuntu 命令:
from subprocess import call
call(["amixer", "-D", "pulse", "sset", "Master", "10%+"])
Run Code Online (Sandbox Code Playgroud)
将增加 10%。
我的代词是他/他