Hi.
How can i open a mp3 file and play it in python?
There is a mp3 file on my Linux desktop and i want to open it from a python file and play it.
What should i do?

The easiest way would be to install a python game/media library like pygame, pyglet or pySFML and use that to play your mp3. There are plenty of other media libraries with python language bindings.

Search your Linux distros package lists for one of the above python modules, or you could install pip (the python2.x package manager) or pip3 (for python3) and use that to install the appropriate library instead.

The exact installation instructions will depend on which Linux distribution you have installed.

There are some examples using various python media libraries here:
http://guzalexander.com/2012/08/17/playing-a-sound-with-python.html

pyglet looks like it will require the least code!

Thank you @JasonHippy.
I'm using Linux; ubuntu.
I've installed pyglet and have copied this code from the link you gave me(just changed the name of mp3 file). And there is the error i got....

The code:

#!/usr/bin/python2
import pyglet
song = pyglet.media.load('linkin_park-Until_Its_Gone-(IroMusic)-193.mp3')
song.play()
pyglet.app.run()

The error:

Traceback (most recent call last):
  File "melody.py", line 3, in <module>
    song = pyglet.media.load('linkin_park-Until_Its_Gone-(IroMusic)-193.mp3')
  File "/usr/lib/pymodules/python2.7/pyglet/media/__init__.py", line 1386, in load
    source = _source_class(filename, file)
  File "/usr/lib/pymodules/python2.7/pyglet/media/riff.py", line 202, in __init__
    'AVbin is required to decode compressed media')
pyglet.media.riff.WAVEFormatException: AVbin is required to decode compressed media
AL lib: (EE) alc_cleanup: 1 device not closed

What's the problem? Could you give a short simple example yourself please?

Look's like you need Avbin
An other option is to use your favorite player.

import subprocess

# pick an external mp3 player you have
sound_program = "path to player"
# pick a sound file you have
sound_file = "path to mp3"
subprocess.call([sound_program, sound_file])

Sooner or later you will use the pygame module anyway ...

''' pg_playmp3f.py
play MP3 music files using Python module pygame
pygame is free from: http://www.pygame.org
(does not create a GUI frame in this case)
'''

import pygame as pg

def play_music(music_file, volume=0.8):
    '''
    stream music with mixer.music module in a blocking manner
    this will stream the sound from disk while playing
    '''
    # 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 best sound)
    pg.mixer.init(freq, bitsize, channels, buffer)
    # volume value 0.0 to 1.0
    pg.mixer.music.set_volume(volume)
    clock = pg.time.Clock()
    try:
        pg.mixer.music.load(music_file)
        print("Music file {} loaded!".format(music_file))
    except pg.error:
        print("File {} not found! ({})".format(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 give the full file path
# (try other sound file formats too)
music_file = "Hot80s.mp3"

# optional volume 0 to 1.0
volume = 0.8

play_music(music_file, volume)

Yes!!!!!!!!!! :) It works thank you @vegaseat.

And thak you all.

@vegaseat, could you please explain this code more clearly to me?! I can't understand some parts clearly. I have written comments:

import pygame as pg

#here why we should type volume=0.8 here? what does it work?
def play_music(music_file, volume=0.8):
    '''
    stream music with mixer.music module in a blocking manner
    this will stream the sound from disk while playing
    '''
    # 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 best sound)

    #could you explaine this line more clear please?
    pg.mixer.init(freq, bitsize, channels, buffer)

    # volume value 0.0 to 1.0   #and also this line?
    pg.mixer.music.set_volume(volume)

    #could you please explain completely each line, one by one please? i don't understand them clearly.
    clock = pg.time.Clock()
    try:
        pg.mixer.music.load(music_file)
        print("Music file {} loaded!".format(music_file))
    except pg.error:
        print("File {} not found! ({})".format(music_file, pg.get_error()))
        return
    pg.mixer.music.play()
    while pg.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)


#### this part is ok i understand.
music_file = "linkin_park-Until_Its_Gone-(IroMusic)-193.mp3"

# optional volume 0 to 1.0
volume = 0.8

play_music(music_file, volume)

Thank you.

And also i have a question, well, i'm confused, which media player on my OS is playing the mp3 file?!

You can create your own media player by reading the posts above, or you could do what I did for my program FindADownload(www.findadownload.net), and let the OS automatically decide how to play the MP3.

You can do so, like this:

import os

os.startfile(NAMEOFFILE)

@Froweey:
os.startfile is Windows only. It doesn't exist for Unix/Linux based OSes.

To use a specific program to open a file on Unix/Linux, then you would need to use Pythons subprocess module as per snippsats previous post!

In linux, you can use subprocess.call(['xdg-open','NAMEOFFILE']).

in line
def play_music(music_file, volume=0.8):
volume=0.8 is the default volume in case you did not supply a value

Basic Python knowledge!

Line
pg.mixer.init(freq, bitsize, channels, buffer)
initializes the pygame mixer (player) with the given arguments

while pg.mixer.music.get_busy():
is the pygame event loop

These lines explain themselves:
pg.mixer.music.load(music_file)
pg.mixer.music.play()

Thank you @vegaseat.

And thank you @gribouillis for the command.

And thank you all for all answers.

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.