Changing volume in Python program on Raspbery Pi
Solution 1
You can use the package python-alsaaudio. The installation and usage is very simple.
To install run:
sudo apt-get install python-alsaaudio
In your Python script, import the module:
import alsaaudio
Now, you need to get the main mixer and get/set the volume:
m = alsaaudio.Mixer()
current_volume = m.getvolume() # Get the current Volume
m.setvolume(70) # Set the volume to 70%.
If the line m = alsaaudio.Mixer()
throws an error, then try:
m = alsaaudio.Mixer('PCM')
this might happen because the Pi uses PCM rather than a Master channel.
You can see more information about your Pi's audio channels, volume (etc..), by running the command amixer
.
Solution 2
- Collecting actual mixers available (will provide a list of available cards):
import alsaaudio as audio
scanCards = audio.cards()
print("cards:", scanCards)
In my case I've got following list:
[u'PCH', u'headset']
- Scanning for the mixers per each card:
for card in scanCards:
scanMixers = audio.mixers(scanCards.index(card))
print("mixers:", scanMixers)
In my case I've got the following two lists:
[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']
As you may see, "Master" is not always the mixer available, but traditionally expected an equivalent of the Master mixer to be at index 0. (Doesn't mean always!)
- To control volume in this case for the USB Headset would be following procedure.
Volume Up
def volumeMasterUP():
mixer = audio.Mixer('Headphone', cardindex=1)
volume = mixer.getvolume()
newVolume = int(volume[0])+10
if newVolume <= 100:
mixer.setvolume(newVolume)
Volume Down
def volumeMasterDOWN():
mixer = audio.Mixer('Headphone', cardindex=1)
volume = mixer.getvolume()
newVolume = int(volume[0])-10
if newVolume >= 0:
mixer.setvolume(newVolume)
Solution 3
I made a simple python service for a two button volume control. Based on what @ant0nisk put.
https://gist.github.com/peteristhegreat/3c94963d5b3a876b27accf86d0a7f7c0
It shows getting and setting the volume, and muting.
Kuba
Updated on June 14, 2022Comments
-
Kuba almost 2 years
I use Raspbery Pi B+ 2. I have a Python program that uses the ultrasonic sensor to measure the distance to an object. What I would like to is change the volume depending on the distance to a human. Having a Python code to obtain the distance, I have no idea, how can I change the Raspbery Pi volume by a code in Python.
Is there any way to do that?
-
Joseph Sheedy over 4 yearsThe package is named pyalsaaudio