【发布时间】:2019-05-14 02:17:21
【问题描述】:
我使用 Raspbery Pi B+ 2。我有一个 Python 程序,它使用超声波传感器测量到物体的距离。我想要的是根据与人的距离来改变音量。有一个Python代码来获取距离,我不知道如何通过Python中的代码来改变树莓派的体积。
有什么办法吗?
【问题讨论】:
标签: python-2.7 raspberry-pi raspberry-pi2
我使用 Raspbery Pi B+ 2。我有一个 Python 程序,它使用超声波传感器测量到物体的距离。我想要的是根据与人的距离来改变音量。有一个Python代码来获取距离,我不知道如何通过Python中的代码来改变树莓派的体积。
有什么办法吗?
【问题讨论】:
标签: python-2.7 raspberry-pi raspberry-pi2
您可以使用包python-alsaaudio。 安装使用非常简单。
要安装运行:
sudo apt-get install python-alsaaudio
在您的 Python 脚本中,导入模块:
import alsaaudio
现在,您需要获取主混音器并获取/设置音量:
m = alsaaudio.Mixer()
current_volume = m.getvolume() # Get the current Volume
m.setvolume(70) # Set the volume to 70%.
如果m = alsaaudio.Mixer()这行抛出错误,那么试试:
m = alsaaudio.Mixer('PCM')
这可能是因为树莓派使用 PCM 而不是主通道。
您可以通过运行命令amixer 来查看有关 Pi 的音频通道、音量(等等)的更多信息。
【讨论】:
import alsaaudio as audio
scanCards = audio.cards()
print("cards:", scanCards)
就我而言,我有以下列表:
[u'PCH', u'headset']
for card in scanCards:
scanMixers = audio.mixers(scanCards.index(card))
print("mixers:", scanMixers)
就我而言,我有以下两个列表:
[u'Master', u'Headphone', u'Speaker', u'PCM', u'Mic', u'Mic Boost', u'IEC958', u'IEC958', u'IEC958', u'IEC958', u'IEC958', u'Beep', u'Capture', u'Auto-Mute Mode', u'Internal Mic Boost', u'Loopback Mixing']
[u'Headphone', u'Mic', u'Auto Gain Control']
如您所见,“Master”并不总是可用的混音器,但传统上认为 Master 混音器的等价物位于索引 0 处。(并不意味着总是!)
def volumeMasterUP():
mixer = audio.Mixer('Headphone', cardindex=1)
volume = mixer.getvolume()
newVolume = int(volume[0])+10
if newVolume <= 100:
mixer.setvolume(newVolume)
def volumeMasterDOWN():
mixer = audio.Mixer('Headphone', cardindex=1)
volume = mixer.getvolume()
newVolume = int(volume[0])-10
if newVolume >= 0:
mixer.setvolume(newVolume)
【讨论】:
我为两个按钮的音量控制制作了一个简单的 python 服务。基于@ant0nisk 所说的。
https://gist.github.com/peteristhegreat/3c94963d5b3a876b27accf86d0a7f7c0
它显示获取和设置音量,以及静音。
【讨论】: