我如何将音量添加到 pyalsaaudio 中的 current_volume 列表?

How would I add volume on to the current_volume list in pyalsaaudio?

我正在尝试将音量增加到当前设置的音量,在这种情况下我们会说它是 80%。使用Python中的alsaaudio模块,有一个函数叫做getvolume

#declare alsaaudio
am = alsaaudio.Mixer()
#get current volume
current_volume = am.getvolume()
在我的例子中,

getvolumecurrent_volume 转储一个列表,例如 [80L] 的 80% 音量。我正在尝试像这样将音量增加到当前音量,

#adds 5 on to the current_volume    
increase = current_volume + 5
am.setvolume(increase)

但我的问题是,因为它是一个列表,所以我不能删除或替换字符,而且由于我对 Python 比较陌生,不知道如何删除列表中的字符然后添加 5转换后为该整数。

我在这里创建了一个 运行-able 示例:

import alsaaudio
am = alsaaudio.Mixer()
current_volume = am.getvolume()
print(repr(current_volume), type(current_volume), type(current_volume[0]))

它打印: ('[45L]', <type 'list'>, <type 'long'>),虽然这个问题已经解决了,感谢您的回复。

Mixer.getvolume([direction])

Returns 包含每个频道当前音量设置的列表。列表元素是整数百分比。

https://www.programcreek.com/python/example/91452/alsaaudio.Mixer

    mixer = alsaaudio.Mixer()
    value = mixer.getvolume()[0]
    value = value + 5
    if value > 100:
        value = 100
    mixer.setvolume(value)

根据 docs, Mixer.getvolume returns a list of integer percentages, with one element for each channel. The docs for Mixer.setvolume 不太清楚,但似乎暗示第一个参数是整数。

如果我的解释是正确的,而你只有一个频道,你可以使用 list indexing to get the first element of the list as an integer. The other steps are as you show in the question. You may want to make sure that the incremented result is less than or equal to 100. The min 函数提供的标准习语来做到这一点:

import alsaaudio

am = alsaaudio.Mixer()
current_volume = am.getvolume()
new_volume = min(current_volume[0] + 5, 100)
am.setvolume(new_volume)

我已将 issue #58 提交给 pyalsaaudio 以澄清文档。