Hey guys, I just want to know if there is any ways to add music to a python program (non-GUI, pure text program), and if there is, how?

Thanks a lot!

9 Years
Discussion Span
Last Post by Ene Uran

You can use module pygame in your program and play MP3 music files without having to create a GUI window:

# play a MP3 music file using module pygame
# (does not create a GUI frame in this case)
# pygame is free from: http://www.pygame.org/
# ene

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()
        print "Music file %s loaded!" % music_file
    except pygame.error:
        print "File %s not found! (%s)" % (music_file, pygame.get_error())
    while pygame.mixer.music.get_busy():
        # check if playback has finished

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

# 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

except KeyboardInterrupt:
    # if user hits Ctrl/C then exit
    # (works only in console mode)
    raise SystemExit

There is a great module called winsound.

import winsound

Just make sure to change the name of the file. FOr more reference check out this page:

Thanks, this seems very easy. But can it only play .wav files? Is there a way to play mp3 files? Thanks a lot!


This is an example from the pyMedia website that will play things for you. Note that you need command line arguments for this, if you want to change this just use things like raw_inputs().

#! /bin/env python

import sys


def aplayer( name, card, rate, tt ):
  import pymedia.muxer as muxer, pymedia.audio.acodec as acodec, pymedia.audio.sound as sound
  import time
  dm= muxer.Demuxer( str.split( name, '.' )[ -1 ].lower() )
  snds= sound.getODevices()
  if card not in range( len( snds ) ):
    raise 'Cannot play sound to non existent device %d out of %d' % ( card+ 1, len( snds ) )
  f= open( name, 'rb' )
  snd= resampler= dec= None
  s= f.read( 32000 )
  t= 0
  while len( s ):
    frames= dm.parse( s )
    if frames:
      for fr in frames:
        # Assume for now only audio streams

        if dec== None:
          print dm.getInfo(), dm.streams
          dec= acodec.Decoder( dm.streams[ fr[ 0 ] ] )
        r= dec.decode( fr[ 1 ] )
        if r and r.data:
          if snd== None:
            print 'Opening sound with %d channels -> %s' % ( r.channels, snds[ card ][ 'name' ] )
            snd= sound.Output( int( r.sample_rate* rate ), r.channels, sound.AFMT_S16_LE, card )
            if rate< 1 or rate> 1:
              resampler= sound.Resampler( (r.sample_rate,r.channels), (int(r.sample_rate/rate),r.channels) )
              print 'Sound resampling %d->%d' % ( r.sample_rate, r.sample_rate/rate )
          data= r.data
          if resampler:
            data= resampler.resample( data )
          if EMULATE:
            # Calc delay we should wait to emulate snd.play()

            d= len( data )/ float( r.sample_rate* r.channels* 2 )
            time.sleep( d )
            if int( t+d )!= int( t ):
              print 'playing: %d sec\r' % ( t+d ),
            t+= d
            snd.play( data )
    if tt> 0:
      if snd and snd.getPosition()> tt:
    s= f.read( 512 )

  while snd.isPlaying():
    time.sleep( .05 )

# ----------------------------------------------------------------------------------

# Play any compressed audio file with adjustable pitch

# http://pymedia.org/

if len( sys.argv )< 2 or len( sys.argv )> 5:
  print "Usage: aplayer <filename> [ sound_card_index, rate( 0..1- slower, 1..4 faster ) ]"
  i= 0
  r= 1
  t= -1
  if len( sys.argv )> 2 :
    i= int( sys.argv[ 2 ] )
  if len( sys.argv )> 3 :
    r= float( sys.argv[ 3 ] )
  if len( sys.argv )> 4 :
    t= int( sys.argv[ 4 ] )
  aplayer( sys.argv[ 1 ], i, r, t )
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.