85

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")
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
The Mr. Totardo
  • 1,119
  • 2
  • 10
  • 11
  • 1
    Check out [pygame](http://www.pygame.org/news.html), and read [this](http://raspberrypi.stackexchange.com/questions/7088/playing-audio-files-with-python) question on raspberrypi.stackexchange. – Steinar Lima Nov 16 '13 at 17:36
  • Possible duplicate of [Playing MP3 files with Python](http://stackoverflow.com/questions/1804366/playing-mp3-files-with-python) – user Jun 19 '16 at 22:32
  • try [just_playback](https://github.com/cheofusi/just_playback) – droptop Sep 14 '21 at 11:09

17 Answers17

121

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.

Ben
  • 3,981
  • 2
  • 25
  • 34
  • 6
    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 - https://wiki.videolan.org/Python_bindings – David Sep 16 '15 at 05:22
  • 1
    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. – Ben Sep 25 '15 at 11:52
  • 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. – Ben Sep 25 '15 at 12:42
  • 3
    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. – Nagabhushan S N Nov 05 '19 at 03:33
  • 2
    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` – JayL Aug 12 '20 at 16:50
87

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)
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
  • 1
    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. – Grimmy Mar 29 '17 at 17:12
  • I will try in python3 but not be working for me any suggestion!! – Harshit Trivedi May 09 '18 at 06:49
  • @HarshitTrivedi what is the error you get? Or does the music simply not play? If so, make sure the mp3 is playable. – shad0w_wa1k3r May 09 '18 at 07:44
  • @AshishNitinPatil when I run this code with giving proper mp3 in python3 but not to play anything – Harshit Trivedi May 09 '18 at 09:04
  • Tested it again on my Python 3.6 on Ubuntu 18.04 and it's working nicely. You're possibly muted or some other silly issue. Kindly check @HarshitTrivedi Try playing the mp3 independently on VLC or something, then try multiple mp3 files (VLC can play anything) with python. – shad0w_wa1k3r May 09 '18 at 09:38
  • Also, the 2nd answer is actually better than mine, so you could try that instead - https://stackoverflow.com/a/25899180/2689986 – shad0w_wa1k3r May 09 '18 at 09:40
  • 1
    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) – Samie Bencherif Feb 11 '19 at 19:33
  • Is it necessary to "free" the file or the mixer after this? – Filipe Pinto Nov 11 '19 at 20:55
  • @FilipePinto As per the documentation and answers on [this question](https://stackoverflow.com/questions/7746263/how-can-i-play-an-mp3-with-pygame), no. – shad0w_wa1k3r Nov 12 '19 at 10:04
  • I have generate a MP3 sound file using gTTS which requires the output to be saved to disk. After this I reproduce/play the output using the code above. I can only do it once because gTTS is unable to overwrite the file the second time. I also cannot delete the file on windows explorer because it is "locked" by python. Everything works fine if I don't use the code above. – Filipe Pinto Nov 14 '19 at 22:11
  • @FilipePinto Can you try using the [vlc method](https://stackoverflow.com/a/25899180/2689986) and see if that also locks your file? – shad0w_wa1k3r Nov 14 '19 at 22:55
  • "Installation is simple"... *sometimes.* – Captain Jack Sparrow Mar 20 '20 at 15:00
  • On Raspbian Lite this requires installation of the `libsdl2-dev` package (per https://stackoverflow.com/a/64332558/11582827) and possibly others. This pulls lots of other packages due to dependencies. – Vlad Jan 19 '22 at 21:53
41

See also playsound

pip install playsound
import playsound
playsound.playsound('/path/to/filename.mp3', True)
TheGoldenTree
  • 158
  • 4
  • 16
Morty
  • 746
  • 5
  • 12
  • 8
    This library has a history of problems on Linux, unfortunately: https://github.com/TaylorSMarks/playsound/issues/1 – Gorkamorka Feb 18 '17 at 14:37
  • 1
    The problems have been fixed :D – TheTechRobo the Nerd Dec 06 '20 at 17:15
  • error- tried on raspberry pi https://gist.github.com/gartha1/e287100003f93b01bdaa9f565590dc47 – barlop Oct 06 '21 at 20:58
  • @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. https://github.com/TaylorSMarks/playsound/issues/81#issuecomment-890659689 – ArtOfWarfare Oct 08 '21 at 00:06
  • Looks good but it doesn't seem to have any events, therefore I cannot control when the sound is over. – Hola Soy Edu Feliz Navidad Dec 12 '21 at 00:41
22

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") 
Wael Almadhoun
  • 401
  • 4
  • 7
21

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
Michael
  • 7,316
  • 1
  • 37
  • 63
15

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.

António Almeida
  • 9,620
  • 8
  • 59
  • 66
David
  • 875
  • 6
  • 6
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')
mdeff
  • 1,566
  • 17
  • 21
8

A simple solution:

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

cheers...

toufikovich
  • 794
  • 1
  • 6
  • 19
  • 1
    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. – Ben Sep 25 '15 at 12:56
  • Thank you Michael, but how i can add "playlist" instead one file? – Amaroc Jul 24 '16 at 23:31
8

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.

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...).

4br3mm0rd
  • 543
  • 3
  • 26
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)
dentex
  • 3,223
  • 4
  • 28
  • 47
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()
MilkyWay90
  • 2,023
  • 1
  • 9
  • 21
hsyn
  • 31
  • 1
2

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)
Appaji Chintimi
  • 613
  • 2
  • 7
  • 19
2

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.

EelkeSpaak
  • 2,757
  • 2
  • 17
  • 37
2

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("")
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/

Petr L.
  • 414
  • 5
  • 13
-3
import os
os.system('file_path/filename.mp3')
Aprillion
  • 21,510
  • 5
  • 55
  • 89
  • 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. – Ben Aug 11 '18 at 07:45
  • it probably works on windows. But I would have used `os.startfile` instead. – Jean-François Fabre Apr 11 '19 at 20:57