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")
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")
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.
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.
$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)
See also playsound
pip install playsound
import playsound
playsound.playsound('/path/to/filename.mp3', True)
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")
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
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.
If you're working in the Jupyter (formerly IPython) notebook, you can
import IPython.display as ipd
ipd.Audio(filename='path/to/file.mp3')
A simple solution:
import webbrowser
webbrowser.open("C:\Users\Public\Music\Sample Music\Kalimba.mp3")
cheers...
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.
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...).
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)
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()
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)
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
.
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("")
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/
import os
os.system('file_path/filename.mp3')