Monday, 18 April 2016

Basic Mp3 Player in Python

You'll need to test for below modules if present in your linux machines
  1. Python - Just type python and you'll get something like below if you already have python installed.

     2. gst-launch-0.10 - Try below command and you will hear a Bell ringing, if not try to install it.
               gst-launch-0.10 audiotestsrc ! audioconvert ! audioresample ! pulsesink

     3. Python curses module - Try import curses in python.


Snapshot of the player:






Code:

#list all songs from the given directory    
def song_input():
    songs = (subprocess.check_output(["locate","-e","-L","*.mp3"]).split('\n'))
    return songs

#Play arugmented passed song using Popen and gst-launch-0.10
def player(Song):

    #Check if any process is running song, if yes then kills it before starting new one
    if processes:
        processes.pop().terminate()
    song="location="+Song
    song_process = subprocess.Popen(["gst-launch-0.10","-q", "filesrc", song," ! mad ! audioconvert ! alsasink"])
    processes.append(song_process)
    return

#curses used to select song from terminal based UI, then sends request to play to played function
def song_selection():
    screen.border()
    screen.nodelay(0)
    curses.noecho()
    selection = -1
    song_name = []
    count = 0
    song_name = song_input()
    while selection < 0:
        screen.clear()
        screen.addstr(dims[0]/2-2,dims[1]/2-len(song_name[count - 2].split('/')[-1])/2,(song_name[count - 2]).split('/')[-1])
        screen.addstr(dims[0]/2-1,dims[1]/2-len(song_name[count - 1].split('/')[-1])/2,(song_name[count - 1]).split('/')[-1])
        screen.addstr(dims[0]/2  ,dims[1]/2-len(song_name[count    ].split('/')[-1])/2,(song_name[count    ].split('/')[-1]),curses.A_BOLD|curses.A_REVERSE)
        screen.addstr(dims[0]/2+1,dims[1]/2-len(song_name[(count + 1) % len(song_name)].split('/')[-1])/2,(song_name[(count + 1) % len(song_name)]).split('/')[-1])
        screen.addstr(dims[0]/2+2,dims[1]/2-len(song_name[(count + 2) % len(song_name)].split('/')[-1])/2,(song_name[(count + 2) % len(song_name)]).split('/')[-1])
        screen.refresh()
        action = screen.getch()
        if action == curses.KEY_UP:
            count = (count - 1) % (len(song_name)-1)
        elif action == curses.KEY_DOWN:
            count = (count + 1) % (len(song_name)-1)
        elif action == ord('\n'):
                player(song_name[count])
        else:
            return


#Script starts Here
#required imports

import curses
import subprocess

processes=[]

screen = curses.initscr()
dims = screen.getmaxyx()
screen.keypad(1)
curses.curs_set(0)
song_selection()
while processes:
    processes.pop().terminate()
curses.endwin()

No comments:

Post a Comment