Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing mp3 song on python

Tags:

python

audio

mp3

I want to play my song (mp3) from python, can you give me a simplest command to do that?

This is not correct:

import wave w = wave.open("e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3","r") 
like image 470
The Mr. Totardo Avatar asked Nov 16 '13 17:11

The Mr. Totardo


People also ask

Can Python read mp3 files?

Conclusion: Playing and Recording Sound in Python You are now able to: Play a large range of audio formats, including WAV, MP3 and NumPy arrays. Record audio from your microphone to a NumPy or Python array.

Can we play a song in Python?

You can play sound files with the pydub module. It's available in the pypi repository (install with pip). This module can use PyAudio and ffmpeg underneath.


2 Answers

Grab the VLC Python module, vlc.py, which provides full support for libVLC and pop that in site-packages. Then:

>>> import vlc >>> p = vlc.MediaPlayer("file:///path/to/track.mp3") >>> p.play() 

And you can stop it with:

>>> p.stop() 

That module offers plenty beyond that (like pretty much anything the VLC media player can do), but that's the simplest and most effective means of playing one MP3.

You could play with os.path a bit to get it to find the path to the MP3 for you, given the filename and possibly limiting the search directories.

Full documentation and pre-prepared modules are available here. Current versions are Python 3 compatible.

like image 117
Ben Avatar answered Sep 21 '22 15:09

Ben


Try this. It's simplistic, but probably not the best method.

from pygame import mixer  # Load the popular external library  mixer.init() mixer.music.load('e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3') mixer.music.play() 

Please note that pygame's support for MP3 is limited. Also, as pointed out by Samy Bencherif, there won't be any silly pygame window popup when you run the above code.

Installation is simple -

$pip install pygame 

Update:

Above code will only play the music if ran interactively, since the play() call will execute instantaneously and the script will exit. To avoid this, you could instead use the following to wait for the music to finish playing and then exit the program, when running the code as a script.

import time from pygame import mixer   mixer.init() mixer.music.load("/file/path/mymusic.ogg") mixer.music.play() while mixer.music.get_busy():  # wait for music to finish playing     time.sleep(1) 
like image 34
shad0w_wa1k3r Avatar answered Sep 24 '22 15:09

shad0w_wa1k3r