Remember this is one of the simplest mp3 player you can create. First, we have to copy some mp3 files into the folder where you save the program (or copy to any folder and use the path to that folder).
Open a new blank file in tour text editor. (I use IDLE).
As initial step we have to import necessary libraries. Here the vlc.py module is provided be VideoLAN.org. You can download it and save in your python file folder.
import vlc
import os
import numpy as np
We define a new instance of the vlc object.
Ins = vlc.Instance()
Then we define following variables.
ListCount = 0
ListMove= “”
Lets define a function ‘mp3serch’ which searches mp3 files using a ‘for’ loop and os.walk() function. The function will return ‘mp3Files’ array with a list of mp3 files or else it will return a blank array / null set if there are no mp3 files.
def mp3serch(mp3path):
mp3Files = []
for (dirpath, dirnames, filenames) in os.walk(mp3path):
for partFile in filenames:
fileExten = partFile[-4:]
if fileExten == ‘.mp3’:
mp3Files.append(partFile)
return mp3Files
Now let’s call the function with giving the file path as the parameter. The ‘./’ indicate it will use the folder where you have saved your script.
MyPlayList = mp3serch(‘./’)
After grabbing some mp3 files, let’s loop through ‘mp3Files’ one-by-one. We can loop through the list of mp3 between first file name and last file name.
while ListCount<len(mp3Files):
Create a new media player instance.
Mp3Player = Ins.media_player_new()
MediaFile = Ins.media_new(mp3Files[ListCount])
The new media player is set to play first item in the mp3 file array.
Mp3Player.set_media(MediaFile)
Mp3Player.play()
If you want you can display the file name of currently playing file. And at the same time a prompt will appear asking you the insert a letter ‘n’, ‘p’ or ‘q’
print “Now Playing : “, mp3Files[ListCount]
ListMove = raw_input(‘Press a key [n for next,p for prev,q for quit]:’)
If ‘q’ is entered then, the program will be quited.
if ListCount>len(mp3Files) or ListMove==’q’:
Mp3Player.stop()
print “Closed”
break
If the ‘n’ is entered then the program would be stopped current play and go to next file and start play.
elif ListMove==’n’:
ListCount +=1
Mp3Player.stop()
If you want to play previous file then, enter ‘p’.
if ListCount>0 and ListMove==’p’:
ListCount -=1
Mp3Player.stop()
You can’t select previous file when you are in the first item of the array. If you pressed ‘p’ accidently it will remind you that “You are still at the begining of the List!”.
elif ListCount<1 and ListMove==’p’:
print “You are still at the begining of the List!”
ListCount=ListCount
Mp3Player.stop()
Save the file as mp3player.py
run it. (If you are using IDLE, press F5)
Please download the code here.