93

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") 
3
  • 1
    Check out pygame, and read this question on raspberrypi.stackexchange. Commented Nov 16, 2013 at 17:36
  • Possible duplicate of Playing MP3 files with Python Commented Jun 19, 2016 at 22:32
  • try just_playback Commented Sep 14, 2021 at 11:09

17 Answers 17

127

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This is likely the best answer as VLC has done 99% of the work. PyPi version is out dated but the VLC wiki is a good alternative src - wiki.videolan.org/Python_bindings
I think the PyPI version was compiled from an older version of VLC and there was definitely differences between 2.1.x and 2.2 which broke things. Compiling VLC from source with the vlc.py generation should always produce a working copy because vlc.py will always have the correct ctypes set for the compiled version of libvlc.
Scatch that, the version on PyPI is a completely unrelated thing. The result of someone writing their own wrapper and not checking for a naming conflict with the original project and similar to the python-gnupg vs. gnupg conflict (except in that case the second project deliberately set out to sabotage the first). No doubt there are others. I guess that's one thing java got right in order to guarantee different and unique names.
Worked, but with a caveat. It used play for a moment and end (since this was the last line of my program). I had to put another line time.sleep(10) and then this played the audio completely.
On Ubuntu in 2020: This won't work when VLC is installed via snap (which is the current recommended way by VLC). Simply install via sudo apt-get install vlc
92

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) 

13 Comments

Tester out pygame's mixer and it seems to a lot less intrusive than pyglet's media player. Probably because pyglet's player is also a video player, so if you don't need video it's a bit overkill! It's a shame pybass don't have python 3 support. That used to be the bomb.
I will try in python3 but not be working for me any suggestion!!
@HarshitTrivedi what is the error you get? Or does the music simply not play? If so, make sure the mp3 is playable.
@AshishNitinPatil when I run this code with giving proper mp3 in python3 but not to play anything
If you're apprehensive about using this because you do not want a pygame window to pop up notice that there is no pygame.init so this will be window free 🎉 (tested on mbp)
|
43

See also playsound

pip install playsound 
import playsound playsound.playsound('/path/to/filename.mp3', True) 

5 Comments

This library has a history of problems on Linux, unfortunately: github.com/TaylorSMarks/playsound/issues/1
The problems have been fixed :D
@barlop - I wrote what I think it'll take to support Rasperry Pi in this comment on github. I think it'd take an hour or three to get it all done. Feel free to do it and make a PR - assuming you get Travis to run and pass the tests, I'll be happy to accept it. github.com/TaylorSMarks/playsound/issues/…
Looks good but it doesn't seem to have any events, therefore I cannot control when the sound is over.
24

I have tried most of the listed options here and found the following:

for windows 10: similar to @Shuge Lee answer;

from playsound import playsound playsound('/path/file.mp3') 

you need to run:

$ pip install playsound 

for Mac: simply just try the following, which runs the os command,

import os os.system("afplay file.mp3") 

3 Comments

playsound requires pygame
@leopd How? I dont have pygame and I can use playsound
I had to try an alternative to playsound as it stopped working after about 30 mp3 files played, same count each time (was not found, scripted) - so far pygame's mixer is working well / not failing after the same test
22

As it wasn't already suggested here, but is probably one of the easiest solutions:

import subprocess def play_mp3(path): subprocess.Popen(['mpg123', '-q', path]).wait() 

It depends on any mpg123 compliant player, which you get e.g. for Debian using:

apt-get install mpg123 

or

apt-get install mpg321 

Comments

16

You are trying to play a .mp3 as if it were a .wav.

You could try using pydub to convert it to .wav format, and then feed that into pyAudio.

Example:

from pydub import AudioSegment song = AudioSegment.from_mp3("original.mp3") song.export("final.wav", format="wav") 

Alternatively, use pygame, as mentioned in the other answer.

Comments

10

If you're working in the Jupyter (formerly IPython) notebook, you can

import IPython.display as ipd ipd.Audio(filename='path/to/file.mp3') 

Comments

9

Another quick and simple option...

import os os.system('start path/to/player/executable path/to/file.mp3') 

Now you might need to make some slight changes to make it work. For example, if the player needs extra arguments or you don't need to specify the full path. But this is a simple way of doing it.

1 Comment

that is windows only
8

A simple solution:

import webbrowser webbrowser.open("C:\Users\Public\Music\Sample Music\Kalimba.mp3") 

cheers...

2 Comments

Cute, but what if the only browser is lynx or even if the others are available on the system, the user only has command line access? It is a nice little quick & dirty workstation solution, though.
Thank you Michael, but how i can add "playlist" instead one file?
7

I had this problem and did not find any solution which I liked, so I created a python wrapper for mpg321: mpyg321.

You would need to have mpg123 or mpg321 installed on your computer, and then do pip install mpyg321.

The usage is pretty simple:

from mpyg321.mpyg321 import MPyg321Player from time import sleep player = MPyg321Player() # instanciate the player player.play_song("sample.mp3") # play a song sleep(5) player.pause() # pause playing sleep(3) player.resume() # resume playing sleep(5) player.stop() # stop playing player.quit() # quit the player 

You can also define callbacks for several events (music paused by user, end of song...).

Comments

5

At this point, why not mentioning python-audio-tools:

It's the best solution I found.

(I needed to install libasound2-dev, on Raspbian)

Code excerpt loosely based on:
https://github.com/tuffy/python-audio-tools/blob/master/trackplay

#!/usr/bin/python import os import re import audiotools.player START = 0 INDEX = 0 PATH = '/path/to/your/mp3/folder' class TracklistPlayer: def __init__(self, tr_list, audio_output=audiotools.player.open_output('ALSA'), replay_gain=audiotools.player.RG_NO_REPLAYGAIN, skip=False): if skip: return self.track_index = INDEX + START - 1 if self.track_index < -1: print('--> [track index was negative]') self.track_index = self.track_index + len(tr_list) self.track_list = tr_list self.player = audiotools.player.Player( audio_output, replay_gain, self.play_track) self.play_track(True, False) def play_track(self, forward=True, not_1st_track=True): try: if forward: self.track_index += 1 else: self.track_index -= 1 current_track = self.track_list[self.track_index] audio_file = audiotools.open(current_track) self.player.open(audio_file) self.player.play() print('--> index: ' + str(self.track_index)) print('--> PLAYING: ' + audio_file.filename) if not_1st_track: pass # here I needed to do something :) if forward: pass # ... and also here except IndexError: print('\n--> playing finished\n') def toggle_play_pause(self): self.player.toggle_play_pause() def stop(self): self.player.stop() def close(self): self.player.stop() self.player.close() def natural_key(el): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)] def natural_cmp(a, b): return cmp(natural_key(a), natural_key(b)) if __name__ == "__main__": print('--> path: ' + PATH) # remove hidden files (i.e. ".thumb") raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH)) # mp3 and wav files only list file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list) # natural order sorting file_list.sort(key=natural_key, reverse=False) track_list = [] for f in file_list: track_list.append(os.path.join(PATH, f)) TracklistPlayer(track_list) 

1 Comment

I made the experience that python-audio-tools just runs with Python 2, not 3.
4

You should use pygame like this:

from pygame import mixer mixer.init() mixer.music.load("path/to/music/file.mp3") # Music file can only be MP3 mixer.music.play() # Then start a infinite loop while True: print("") 

Comments

3
from win32com.client import Dispatch wmp = Dispatch('WMPlayer.OCX') liste = [r"F:\Mp3\rep\6.Evinden Uzakta.mp3", r"F:\Mp3\rep\07___SAGOPA_KAJMER___BIR__I.MP3", r"F:\Mp3\rep\7.Terzi.mp3", r"F:\Mp3\rep\08. Rüya.mp3", r"F:\Mp3\rep\8.Battle Edebiyatı.mp3", r"F:\Mp3\rep\09_AUDIOTRACK_09.MP3", r"F:\Mp3\rep\02. Sagopa Kajmer - Uzun Yollara Devam.mp3", r"F:\Mp3\rep\2Pac_-_CHANGE.mp3", r"F:\Mp3\rep\03. Herkes.mp3", r"F:\Mp3\rep\06. Sagopa Kajmer - Istakoz.mp3"] for x in liste: mp3 = wmp.newMedia(x) wmp.currentPlaylist.appendItem(mp3) wmp.controls.play() 

Comments

3

So Far, pydub worked best for me. Modules like playsound will also do the job, But It has only one single feature. pydub has many features like slicing the song(file), Adjusting the volume etc...

It is as simple as slicing the lists in python.

So, When it comes to just playing, It is as shown as below.

from pydub import AudioSegment from pydub.playback import play path_to_file = r"Music/Harry Potter Theme Song.mp3" song = AudioSegment.from_mp3(path_to_file) play(song) 

Comments

3

For anyone still finding this in 2020: after a search longer than I expected, I just found the simpleaudio library, which appears well-maintained, is MIT licensed, works on Linux, macOS, and Windows, and only has very few dependencies (only python3-dev and libasound2-dev on Linux).

It supports playing data directly from buffers (e.g. Numpy arrays) in-memory, has a convenient audio test function:

import simpleaudio.functionchecks as fc fc.LeftRightCheck.run() 

and you can play a file from disk as follows:

import simpleaudio as sa wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav") play_obj = wave_obj.play() play_obj.wait_done() 

Installation instructions are basically pip install simpleaudio.

1 Comment

Does not support mp3, though
0

As suggested by Ben, you can use the pyvlc module. But even if you don't have that module, you can play mp3 and mkv files with VLC from Terminal in Linux:

import os os.system('nvlc /home/Italiano/dwhelper/"Bella Ciao Originale.mkv"') 

More information here: https://linuxhint.com/play_mp3_files_commandline/

Comments

-4
import os os.system('file_path/filename.mp3') 

2 Comments

This will not do anything unless the operating system executes audio files solely by entering the path and filename; most, if not all, systems do not do this. Also, use of os.system is strongly discouraged. Use subprocess instead or even sh if you must.
it probably works on windows. But I would have used os.startfile instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.