使用python脚本控制音量
我可以通过终端amixer -D pulse sset Master 0%
使用此命令控制音量。 我的问题是如何使用python脚本执行相同的操作。
您可以使用subprocess
模块中的call
:
from subprocess import call call(["amixer", "-D", "pulse", "sset", "Master", "0%"])
资源
当然,你可以使用普通的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
此代码将循环,直到用户提供有效输入 – 介于0和100之间,然后将音量设置为该输入。
这将在Python 3中运行。将input
更改为Python 2的raw_input
。
要在脚本运行时增加10%,您可以执行以下两项操作之一。
您可以使用alsaaudio
模块。
首先,安装
sudo apt-get install python-alsaaudio
然后导入它:
import alsaaudio
我们可以得到音量:
>>> m = alsaaudio.Mixer() >>> vol = m.getvolume() >>> vol [50L]
我们也可以设置音量:
>>> m.setvolume(20) >>> vol = m.getvolume() >>> vol [20L]
此数字是列表中的长整数 。 所以为了使它成为可用的数字,我们可以做int(vol[0])
。
运行时增加10%?
import alsaaudio m = alsaaudio.Mixer() vol = m.getvolume() vol = int(vol[0]) newVol = vol + 10 m.setvolume(newVol)
或者我们可以坚持使用subprocess
模块和默认的Ubuntu命令:
from subprocess import call call(["amixer", "-D", "pulse", "sset", "Master", "10%+"])
将增加10%。
对我来说,蒂姆的代码不太合适。 我不得不这样做:
import alsaaudio m = alsaaudio.Mixer(alsaaudio.mixers[0]) # alsaaudio.mixers = ["PCM"] for me. m.setvolume(90) # Or whatever
这可能是由于我的奇怪/破坏.asoundrc
配置文件。 但鉴于.asoundrc
没有实际的参考文档 – 只是一些随机的例子 – 我认为你不能怪我。
另外请不要调用命令行程序来执行此操作。 这很丑陋且容易出错。