954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Music in Python

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!

elvenstruggle
Newbie Poster
5 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

There is a great module called winsound.

import winsound
winsound.PlaySound("soundFile.wav",SND_ASYNC)
raw_input()

Just make sure to change the name of the file. FOr more reference check out this page: http://python.active-venture.com/lib/module-winsound.html

Paul Thompson
Veteran Poster
1,119 posts since May 2008
Reputation Points: 264
Solved Threads: 183
 

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()
    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 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
pygame.mixer.music.set_volume(0.8)

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
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
 

You can use PyAudio, or Pymedia (I havent use any but pyaudio is simple by looking with eyes). If that is too light, go for DLLs like Bass. Infact Im working with Bass.DLL and works fine for me, though I'm still learning it!

http://www.un4seen.com/forum/?topic=9271.0

evstevemd
Senior Poster
3,713 posts since Jun 2007
Reputation Points: 462
Solved Threads: 392
 

There is a great module called winsound.

import winsound
winsound.PlaySound("soundFile.wav",SND_ASYNC)
raw_input()

Just make sure to change the name of the file. FOr more reference check out this page: http://python.active-venture.com/lib/module-winsound.html

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

elvenstruggle
Newbie Poster
5 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

I have pointed out bass.dll and pymedia. If you choose bass.dll, you will have to face ctypes and for pure pythonic solutio, go for pymedia
Here are some links for pymedia:
http://pymedia.org/
http://pymedia.org/docs/index.html
http://pymedia.org/tut/index.html

evstevemd
Senior Poster
3,713 posts since Jun 2007
Reputation Points: 462
Solved Threads: 392
 

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

EMULATE=0

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
          else:
            snd.play( data )
    if tt> 0:
      if snd and snd.getPosition()> tt:
        break
    
    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 ) ]"
else:
  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 )
Paul Thompson
Veteran Poster
1,119 posts since May 2008
Reputation Points: 264
Solved Threads: 183
 

PyMedia is older than the hills and hasn't been updated for a few years!

If you are looking for oldies but goodies there is also:
http://pysonic.sourceforge.net/index.html
It uses the ever so popular FMOD.DLL

In case you missed it, the PyGame module will play MP3 files.

Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You