how do i pause a sound / song using python?

690 Views Asked by At

I would like to pause the music / audio of chrome. for example when I receive a specific input the audio of a video stops and then restarts when it receives a specific input, what should I use?

1

There are 1 best solutions below

4
Jake On

You can use something called dbus, and there is even a python library for it.

You will first have to find the name of the media player using the following code.

import dbus

for service in dbus.SessionBus().list_names():
    if ".Media" in service:
        print(service)

You will get a list something like this

org.mpris.MediaPlayer2.spotify
org.mpris.MediaPlayer2.chromium.instance1234
...

In the things printed, find the one that looks to be your browser.

Then the easiest way to run this command is just using subprocess.

import subprocess

subprocess.run(
    [
        "dbus-send",
        "--print-reply",
        "--dest=org.mpris.MediaPlayer2.chromium.instance1234",
        "/org/mpris/MediaPlayer2",
        "org.mpris.MediaPlayer2.Player.PlayPause",
    ],
)

After that, it should pause or play the song.

Note: You don't just have to do PlayPause, there is also Previous and Next and Pause.

If you want to use input, you can do something like this

import subprocess


def pause_play():
    subprocess.run(
        [
            "dbus-send",
            "--print-reply",
            "--dest=org.mpris.MediaPlayer2.chromium.instance63145",
            "/org/mpris/MediaPlayer2",
            "org.mpris.MediaPlayer2.Player.PlayPause",
        ],
    )


if __name__ == "__main__":
    while 1:
        command = input("Enter a command: ")
        if command == "p":
            pause_play()