Fugazi1978
Posts: 21
Joined: Sun Jul 01, 2012 11:43 am

Help - non-GUI python media player...

Sun Jul 01, 2012 11:47 am

Hi, I've written code to search for mp3s in my mp3s folder (which when used on a Pi will be a memory stick). It looks like this:

Code: Select all

import os
loop = 0
os.system('clear')
os.system('ls -1pR mp3s > files.out')
f = open('files.out', 'r')
A = f.readline()
C = ['this','is','a','list']
C[:] = []
if A[-2:-1] == ":":
while loop == 0:
B = f.readline()
if B[-2:-1] == ":":
A = B
if B[-5:-1] == ".mp3":
C[len(C)+1:] = [A[:-2] + '/' + B[:-1]]
if B == "":
loop = 1
All items in C[] look like 'mp3s/Ben_Folds_Five/Whatever_And_Ever_Amen/12-Evaporated.mp3'
I tried using mpg321 to play the tracks but couldn't work out how to play them 1 at a time.
I tried using pyglet.media.Player() but couldn't work anything out at all.
My aim is for a non-GUI media player that will pause/play, go forward a track, go back a track, go forward a folder and go back a folder.
I work on linux (debian) and haven't programmed much for 20 years.
The aim is to stick a non-networked Pi into an old stereo (car), auto log on, auto start the programme and eventually use GPIO connections to do the 5 functions (pause/play, go forward a track, go back a track, go forward a folder and go back a folder). The stereo jack would then be soldered to the amp, replacing the radio.

Any ideas?

Thanks in advance.

timhoffman
Posts: 85
Joined: Sat Nov 05, 2011 11:31 pm

Re: Help - non-GUI python media player...

Mon Jul 02, 2012 12:02 am

Hi

I would look at using the media playback functionality of pygame, it already has most of the features you will want like queue etc...

http://www.pygame.org/docs/ref/music.html

Also to get listings of files in directories us os.walk rather than running stuff via shell and reading the output from a file.

http://docs.python.org/library/os.html? ... lk#os.walk

Cheers

Tim

KenT
Posts: 758
Joined: Tue Jan 24, 2012 9:30 am
Location: Hertfordshire, UK
Contact: Website

Re: Help - non-GUI python media player...

Mon Jul 02, 2012 6:35 am

I'm trying to do exactly the same thing as the OP but to use the GPIO triggered player for a visitor centre or museum exhibit. I want video as well as audio so am trying to use omxplayer

I've managed to write a python interface for omxplayer. My first go is here https://github.com/KenT2/pyomxplayer. Its main problem is that it does not exit properly when the track finishes playing. I think I need to monitor the output of the sub-process through a second pipe and detect 'Have a Nice Day'.
Pi Presents - A toolkit to produce multi-media interactive display applications for museums, visitor centres, and more
Download from http://pipresents.wordpress.com

Fugazi1978
Posts: 21
Joined: Sun Jul 01, 2012 11:43 am

Re: Help - non-GUI python media player...

Mon Jul 02, 2012 1:40 pm

Hi Tim, lots of the functions in pygame look great. Let's just presume I'm slightly thick, just getting back into programming (I played a bit with Fortran 12 years ago and Basic 22 years ago) and thus I'm struggling with every bit of it! How would I make a python/pygame program that played pie.mp3 from the same folder and could send a pause signal (I'll try to work out the rest when I know the rough scripting)?

Thanks,
Matthew.
timhoffman wrote:Hi

I would look at using the media playback functionality of pygame, it already has most of the features you will want like queue etc...

http://www.pygame.org/docs/ref/music.html

Also to get listings of files in directories us os.walk rather than running stuff via shell and reading the output from a file.

http://docs.python.org/library/os.html? ... lk#os.walk

Cheers

Tim

wrhii
Posts: 66
Joined: Fri Nov 18, 2011 1:47 am

Re: Help - non-GUI python media player...

Mon Jul 02, 2012 6:31 pm

Fugazi1978 wrote:... How would I make a python/pygame program that played pie.mp3 from the same folder and could send a pause signal (I'll try to work out the rest when I know the rough scripting)?
Since you said you'd try to work out the rest, I'll give some ideas, but should disclaim having not used Pygame myself.
Source: http://www.python-forum.org/pythonforum ... =10631&f=2
Disclaimer: I googled for: pygame play mp3 python

Code: Select all

# play a MP3 or MIDI music file using module pygame
# (does not create a GUI frame in this case)
# pygame is free from: http://www.pygame.org/
# Tested with pygame-1.8.0 by:  Ene Uran

import pygame

def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(music_file)
        print "Music file %s loaded!" % music_file
    except pygame.error:
        print "File %s not found! (%s)" % (music_file, pygame.get_error())
        return
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)


# pick a MP3 or MIDI music file you have ...
# (if not in working folder, use full path)
music_file = "Drumtrack.mp3"
#music_file = "ChancesAre.mid"

# set up the mixer
freq = 44100     # audio CD quality
bitsize = -16    # unsigned 16 bit
channels = 2     # 1 is mono, 2 is stereo
buffer = 2048    # number of samples (experiment to get right sound)
pygame.mixer.init(freq, bitsize, channels, buffer)

# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.75)

try:
    play_music(music_file)
except KeyboardInterrupt:
    # if user hits Ctrl/C then exit
    # (works only in console mode)
    pygame.mixer.music.fadeout(1000)
    pygame.mixer.music.stop()
    raise SystemExit

rasbeer
Posts: 242
Joined: Wed Mar 07, 2012 8:35 am

Re: Help - non-GUI python media player...

Mon Jul 02, 2012 6:36 pm

timhoffman wrote:Hi

I would look at using the media playback functionality of pygame, it already has most of the features you will want like queue etc...

http://www.pygame.org/docs/ref/music.html
It does say "Be aware that MP3 support is limited. On some systems an unsupported format can crash the program, e.g. Debian Linux. Consider using OGG instead".

I did have a quick look for a more solid MP3 library for Python a while back, but nothing came up.

timhoffman
Posts: 85
Joined: Sat Nov 05, 2011 11:31 pm

Re: Help - non-GUI python media player...

Tue Jul 03, 2012 6:49 am

Some distros don't include mp3 decoders by default and you have to install them seperately. That will effect how well mpeg support is under pygame.

Fugazi1978
Posts: 21
Joined: Sun Jul 01, 2012 11:43 am

Re: Help - non-GUI python media player...

Tue Jul 03, 2012 10:24 pm

I've gone for ogg files:

Code: Select all

import os
import sys
import pygame

loop = 0
esc = 0
os.system('clear')
os.system('ls -1pR music > files.out')
#os.system('egrep -n ".mp3" files.out > mp3s.out')
#os.system('egrep -nv ".mp3" files.out > mp3s2.out')
#os.system('look "mp3s" files.out > folders.out')
f = open('files.out', 'r')
A = f.readline()
C = ['this','is','a','list']
C[:] = []
print A
print A[-2:-1]
if A[-2:-1] == ":":
	while loop == 0:
		B = f.readline()
		if B[-2:-1] == ":":
			A = B
		if B[-5:-1] == ".ogg":
			C[len(C)+1:] = [A[:-2] + '/' + B[:-1]]
		if B == "":
			loop = 1

# set up the mixer
freq = 44100     # audio CD quality
bitsize = -16    # unsigned 16 bit
channels = 2     # 1 is mono, 2 is stereo
buffer = 2048    # number of samples (experiment to get right sound)
pygame.mixer.init(freq, bitsize, channels, buffer)

# optional volume 0 to 1.0
pygame.mixer.music.set_volume(1.0)

track = 0
breaker = 0
clock = pygame.time.Clock()
while breaker == 0:
	pygame.mixer.music.load(C[track])
	pygame.mixer.music.play()
	#    pygame.mixer.music.pause()
	
	# check if playback has finished
	while pygame.mixer.music.get_busy():
		clock.tick(30)
#		if pygame.event.get(pygame.KEYDOWN) == pygame.K_b:
#			pygame.mixer.music.pause()
#		if event.key == pygame.K_n:
#			pygame.mixer.music.stop()
#		if event.key == pygame.K_v:
#			track = track - 2

	track = track + 1
	if track < 0:
		track = len(C) + track
	if track > len(C) - 1:
		track = 0
All I need now is keystroke detection without drawing a window (pure command line).

Fugazi1978
Posts: 21
Joined: Sun Jul 01, 2012 11:43 am

Re: Help - non-GUI python media player...

Wed Jul 04, 2012 2:48 pm

Here's the code for the media player with keystroke detection, unfortunately it plays slowly (anyone any ideas):

Code: Select all

import os
import sys
import pygame
import curses
#pygame.init()
loop = 0
esc = 0
os.system('clear')

# music files (ogg) must be in a folder, 'music', in same folder as program
os.system('ls -1pR music > files.out')

# open list of files
f = open('files.out', 'r')

# create a list C[ ]
C = ['this','is','a','list']

# empty c
C[:] = []

# read first line of files.out
A = f.readline()

# reads all lines of files.out, places full path to each file in C[ ]
while esc == 0:
	if A[-2:-1] == ":":
		while loop == 0:
			B = f.readline()
			if B[-2:-1] == ":":
				A = B
			if B[-5:-1] == ".ogg":
				C[len(C)+1:] = [A[:-2] + '/' + B[:-1]]
			if B == "":
				esc = 1
				loop = 1
	else:
		A = f.readline()

#init the curses screen
stdscr = curses.initscr()

#use cbreak to not require a return key press
curses.cbreak()

track = 0
breaker = 0

# set up the mixer
freq = 44100     # audio CD quality
bitsize = -16    # unsigned 16 bit
channels = 2     # 1 is mono, 2 is stereo
buffer = 2048    # number of samples (experiment to get right sound)
pygame.mixer.init(freq, bitsize, channels, buffer)

# optional volume 0 to 1.0
pygame.mixer.music.set_volume(1.0)

# starts pygame clock
clock = pygame.time.Clock()

while breaker == 0:
	pygame.mixer.music.load(C[track])
	pygame.mixer.music.play()
	pz = 1
	# check if playback has finished
	while pygame.mixer.music.get_busy():
		clock.tick(30)
		# python curses to 'get' keyboard input
		k = stdscr.getch()
		# press b to pause/play track
		if curses.keyname(k)=="b":
			if pz == 1:
				pygame.mixer.music.pause()
				pz = 2
			else:
				pygame.mixer.music.play()
				pz = 1
		# press n to move to next track
		if curses.keyname(k)=="n":
			pygame.mixer.music.stop()
		# press v to go back a track
		if curses.keyname(k)=="v":
			track = track -2
			pygame.mixer.music.stop()
		# press q to quit
		if curses.keyname(k)=="q":
			pygame.mixer.quit()
			breaker = 1
			curses.endwin()
	track = track + 1

	# check track number isn't less than first track
	if track < 0:
		track = len(C) + track

	# check track number isn't more than last track
	if track > len(C) - 1:
		track = 0
It plays ogg files, anywhere from within the 'music' folder that is in the same folder as the program.

Any improvements to the current script greatly appreciated. Requires pygame.

Aim of the program is a command line jukebox with keystroke detection for moving through tracks.

Matthew

wrhii
Posts: 66
Joined: Fri Nov 18, 2011 1:47 am

Re: Help - non-GUI python media player...

Thu Jul 05, 2012 10:43 am

Should try using os.walk to build a listing of files, instead of running the LS command.
http://docs.python.org/library/os.html

Do you mean the playback is slow, or that the execution of the script is slow? Also, you can use the OS.Path to get just filename info, etc... so you can clean-up the script significantly that way, and there are other ways of capturing keyboard input, though you're trying to capture it during execution, so not positive how that will play out exactly in python. I generally use the raw_input command to capture keyboard input, but I suspect it will pause things in the script if you do that. Which, would be bad when you get to the end of a song. :|
Perhaps the below would work (capture with timeout):
http://stackoverflow.com/questions/1335 ... -in-python

Fugazi1978
Posts: 21
Joined: Sun Jul 01, 2012 11:43 am

Re: Help - non-GUI python media player...

Thu Jul 05, 2012 12:55 pm

Some of my oggs were 48000Hz so played slow. I stuck a clumsy rate detector in.

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: Help - non-GUI python media player...

Thu Jul 05, 2012 2:18 pm

would pymedia help to eliminate pygame?

I like this project but being a complete novice i'm just starting to hack away at other peoples code to try and get different actions.

I was thinking that not using pygame might be possible, then the script could be extended so from the library you could create a playlist library etc

Fugazi1978
Posts: 21
Joined: Sun Jul 01, 2012 11:43 am

Re: Help - non-GUI python media player...

Thu Jul 05, 2012 2:25 pm

PyMedia isn't available from the software manager on Linux Mint so I didn't bother (if it's in the manager it is generally pretty sound). I've heard PyMedia does some bits I wanted but the link to my current code (with key detection and correct playback speed) is:

http://www.raspberrypi.org/phpBB3/viewt ... 67#p116367

Next is an ability to progress a folder at a time and remember where it was when you switched the computer off.

Fugazi1978
Posts: 21
Joined: Sun Jul 01, 2012 11:43 am

Re: Help - non-GUI python media player...

Thu Jul 05, 2012 2:26 pm

Also, DON'T LEARN FROM ME, MY SCRIPT SUCKS (though it does work)!

KenT
Posts: 758
Joined: Tue Jan 24, 2012 9:30 am
Location: Hertfordshire, UK
Contact: Website

Re: Help - non-GUI python media player...

Mon Jul 09, 2012 6:42 pm

You could try this, it interfaces python to omxplayer which is the player behind xbmc and uses the GPU for some video playback.

http://www.raspberrypi.org/phpBB3/viewt ... 38&t=10599
Pi Presents - A toolkit to produce multi-media interactive display applications for museums, visitor centres, and more
Download from http://pipresents.wordpress.com

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: Help - non-GUI python media player...

Tue Aug 14, 2012 1:07 pm

Thanks for this KenT,

I have used your code and am currently in the process of writing a bolt on for creating a music catalog and custom playlists.

It runs through all the songs it can see, reads the metadata for those songs and places them into an XML file. Then catalog side is done, but I am still working on the playlist. When I am finished I will post the code.

KenT
Posts: 758
Joined: Tue Jan 24, 2012 9:30 am
Location: Hertfordshire, UK
Contact: Website

Re: Help - non-GUI python media player...

Wed Aug 15, 2012 10:08 pm

Hi steve_300. I've only just seen your post as the phone line has been broken for 2 days :cry:

I've just finished a Tkinter gui media player based on jbaiters pyomxplayer. It reads a playlist from a csv file and plays it with full button and keyboard control. It would be easy for you to add a python function to read your xml files and to expand the information displayed in the gui.

I'll put the code on github tomorrow morning and post here.
Pi Presents - A toolkit to produce multi-media interactive display applications for museums, visitor centres, and more
Download from http://pipresents.wordpress.com

KenT
Posts: 758
Joined: Tue Jan 24, 2012 9:30 am
Location: Hertfordshire, UK
Contact: Website

Re: Help - non-GUI python media player...

Thu Aug 16, 2012 11:43 am

Steve_300

My Gui interface program for omplayer is now on github here:

https://github.com/KenT2/tboplayer

Its a beta release.

It should be possible to replace the function that reads a playlist from a file with a function that reads your XML files.
Pi Presents - A toolkit to produce multi-media interactive display applications for museums, visitor centres, and more
Download from http://pipresents.wordpress.com

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: Help - non-GUI python media player...

Thu Aug 23, 2012 9:55 am

Thanks for this KenT,

I'm going to stick to the GUI aspect for now. I have linked twitter into it now as well so I can tweet a special account that I have set up and tell it to start playing a particular playlist

I don't get much time to work on this so progress is slow but I will publish the code when it gets a bit more complete.

Return to “Python”