Search code examples
pythonaudioubuntugnomealsa

How to programmatically change volume in Ubuntu


How do you programmatically change volume in Gnome on Ubuntu, either from the command line or an API (Python preferrably)?

The only answers I found to similar questions use amixer, which seems to have no effect on Ubuntu 12.04. Running:

amixer set Headphone 10-

shows:

Simple mixer control 'Headphone',0
  Capabilities: pvolume pswitch penum
  Playback channels: Front Left - Front Right
  Limits: Playback 0 - 115
  Mono:
  Front Left: Playback 0 [57%] [-57.50dB] [on]
  Front Right: Playback 0 [57%] [-57.50dB] [on]

The x% changes each time I run it. Unfortunately, it has no effect on the actual volume. Eventually it says 0%, but volume is still at full blast.

The other downside is I have to specify the exact active output device, which I might not know if there are multiple devices. For example, if I have a "Master" and "Headphone", how do I determine which one is the active device?


Solution

  • Ubuntu uses pulseaudio as sounderver. It can be controlled from the command line using the pactl and pacmd utilities, for example:

    pactl set-sink-volume 0 20%
    

    would set the volume of the sink #0 to 20%.

    see: man pactl and pacmd help


    edit:

    to avoid -xx being interpreted as command line option you must prefix it with --. That stops option parsing from that point:

    pactl set-sink-volume 0 -- -20%    # or:
    pactl -- set-sink-volume 0 -20%    # doesn't matter where the `--` goes