1

I'm doing something like a vocal assistant in python. Through different modules, I managed to download a youtube video and convert it to mp3. Now I'd like to play it and being capable of pausing it and other actions. I tried with pygame but I couldn't use it without opening a window. Any suggestion?

Filippo
  • 107
  • 1
  • 2
  • 10

3 Answers3

1

There are good libraries for this. Check here.
Also you can use terminal commands for example :

import os
os.system('xdg-open music.mp3')
# music is playing ...

I use MOC player in cli that can play and pause music on background for example :

import os 
os.system('moc -l music.mp3')    #play music 
os.system('moc -P music.mp3')    #pause music
os.system('moc -U music.mp3')    #unpause music
mo1ein
  • 535
  • 4
  • 18
0

You can use the playsound module in python after installing it with pip like so

from playsound import playsound

playsound('path\to\your\music\file.mp3', False)
  • the False argument lets the sound play in the background
  • sadly this can only work on windows as it is implemented for windows drivers till now
Emlore
  • 3
  • 5
karimkohel
  • 96
  • 1
  • 8
0

By using VLC

first of all, install vlc

$ pip install python-vlc

then you can add this to your code

import vlc

player = vlc.MediaPlayer("/path/to/song.mp3")

player.play()

and just like this, you can play music in the background. you can even control it!

# to pause music
player.pause()

# to stop music
player.stop()

You can make a function like this one

import vlc

player = None

def play_music(path):
    global player
    if player is not None:
        player.stop # this code stop old music (if exist) before starting new one

    player = vlc.MediaPlayer(path)
    player.play()