Skip to content

Instantly share code, notes, and snippets.

@slitayem
Forked from juehan/PyGameMP3Player.py
Created January 13, 2018 13:18
Show Gist options
  • Save slitayem/dc4076a0d2739e70aee7486d7f30c801 to your computer and use it in GitHub Desktop.
Save slitayem/dc4076a0d2739e70aee7486d7f30c801 to your computer and use it in GitHub Desktop.
MP3Player Using PyGame
'''
Created on 2012. 2. 19.
This module is for playing mp3 (limited) and wav formatted audio file
@author: John
'''
import pygame
def playsound(soundfile):
"""Play sound through default mixer channel in blocking manner.
This will load the whole sound into memory before playback
"""
pygame.init()
pygame.mixer.init()
sound = pygame.mixer.Sound(soundfile)
clock = pygame.time.Clock()
sound.play()
while pygame.mixer.get_busy():
print "Playing..."
clock.tick(1000)
def playmusic(soundfile):
"""Stream music with mixer.music module in blocking manner.
This will stream the sound from disk while playing.
"""
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()
pygame.mixer.music.load(soundfile)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
print "Playing..."
clock.tick(1000)
def stopmusic():
"""stop currently playing music"""
pygame.mixer.music.stop()
def getmixerargs():
pygame.mixer.init()
freq, size, chan = pygame.mixer.get_init()
return freq, size, chan
def initMixer():
BUFFER = 3072 # audio buffer size, number of samples since pygame 1.8.
FREQ, SIZE, CHAN = getmixerargs()
pygame.mixer.init(FREQ, SIZE, CHAN, BUFFER)
'''You definitely need test mp3 file (a.mp3 in example) in a directory, say under 'C:\\Temp'
* To play wav format file instead of mp3,
1) replace a.mp3 file with it, say 'a.wav'
2) In try except clause below replace "playmusic()" with "playsound()"
'''
try:
initMixer()
filename = 'C:\\Temp\\a.mp3'
playmusic(filename)
except KeyboardInterrupt: # to stop playing, press "ctrl-c"
stopmusic()
print "\nPlay Stopped by user"
except Exception:
print "unknown error"
print "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment