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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With