Member Avatar for sravan953

Can the sibprocess.call('') function be used to execute .mp3 files, it doesn't work for me. Which function is used to run any video or audio file from within Python?

I believe that subprocess.call is used to open a file as if you had "dobule-clicked" the file's icon. If you're looking to do it "within" python you'll need to search this forum for how others have done it before you.

You can use the module pygame from:
http://www.pygame.org/
Here is a small example ...

# play MP3 music files using Python module pygame
# (does not create a GUI frame in this case)
# modified code from Ene Uran

import pygame as pg

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


# pick a MP3 music file you have in the working folder
# otherwise use the full file path
music_file = "Hot80s.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)
pg.mixer.init(freq, bitsize, channels, buffer)

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

play_music(music_file)

Somewhat simpler is the AudioVisual module pyglet ...

# play an MP3 music file using Python module pyglet
# download pyglet from: http://www.pyglet.org/download.html
# (no GUI window/frame is created)

import pyglet

# pick an MP3 music file you have in the working folder
# otherwise use the full file path
music_file = "Boing.mp3"

music = pyglet.resource.media(music_file)
music.play()

pyglet.app.run()

If you have Windows XP, you can use mplayer2.exe ...

# using Python module subprocess to play
# a sound file on an external program

import subprocess

# pick an external mp3 player you have
# mplayer2.exe works, but not the newer bloated wmplayer.exe
sound_program = "C:/Program Files/Windows Media Player/mplayer2.exe"
# pick a sound file you have
sound_file = "D:/Python25/Atest/Sound/MP3/Hot80s.mp3"

subprocess.call([sound_program, sound_file])

how to attach music files to python program using subprocess.call???

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.