Search code examples
raspberry-pivolume

How to control the volume of raspberry pi with python 3?


I have been looking up the web for any reference to control the volume of raspberry pi (b+) with python script . I come up with this thread previously asked but python-alsaaudio doesn't works with python 3 or say in the thonny python idle . So I need to know any correct way to change the volume of pi as per the user input .


Solution

  • Another way is to control volume through a command line tool. There is a tool for the Alsa command line called amixer:

    amixer sset Master 50%
    

    Now you can create a simple python script that runs the above command:

    import subprocess
    
    
    # a value between 0 and 100
    volume = 50
    command = ["amixer", "sset", "Master", "{}%".format(volume)]
    subprocess.Popen(command)
    

    You can change Master to other soundcards. You can get a list of controls:

    $ amixer scontrols
    
    Simple mixer control 'Master',0
    Simple mixer control 'PCM',0
    Simple mixer control 'Line',0
    Simple mixer control 'CD',0
    Simple mixer control 'Mic',0
    Simple mixer control 'Mic Boost (+20dB)',0
    Simple mixer control 'Video',0
    Simple mixer control 'Phone',0
    Simple mixer control 'IEC958',0
    Simple mixer control 'Aux',0
    Simple mixer control 'Capture',0
    Simple mixer control 'Mix',0
    Simple mixer control 'Mix Mono',0