how to play music with python

Namaste Friends,



Today, In this tutorial I am going to show you how we can play music files in python scripts.


Introduction


Many times in many python projects or scripts we have/need to play with music and sound files. By the way, Listening Music is my favorite way to make my mind stress free and I hope you also like music listening habits. basically, In today's busy life, music is really very beautiful part of our life and of course to run any music.. music playing app is one of the basic requirement.
Actually, In Python, there is no built-in library that can help us in playing an mp3 sound file and produce noise from speakers. Therefore, To play any music file, programmer always needs to take help from any External Or third-party modules. Basically, there are many types of modules that can easily play music files but here, In this tutorial, I am going to use pyglet. well well, there are many reasons to choose pyglet library (Discussed In Below Section ) But The main reason to choose pyglet library is its Cross-Platform Support features. Yes, Yes, With This Library You can easily play music on any Platform without doing changes in Your written codes. hence, before sharing my codes here I am going to write about Pyglet Module.

About Pyglet Module

(You can Skip this section)

 Q 1. What is pyglet? Or Why I am using pyglet?

Ans. As Wikipedia says “Pyglet is a library for the Python programming language that provides an object-oriented application programming interface for the creation of games and other multimedia applications. Pyglet runs on Microsoft WindowsMac OS X, and Linux; it is released under BSD Licence.""  

In Simple Words, This Library basically provides us various types of functionality, Capabilities, Systems, scripts Required to make a rich feature loaded Games And One of the major features of this modules is its cross-platform capability with Object Oriented Programming Interface, And a wide range of media file handling capabilities. 

Well, There are some more other features also available like It supports windowed and full-screen operation, and multiple monitors also. 
More Images, video, and sound files in a range of formats can be done natively, with more additional capabilities supplied by the optional AVbin plugin, which uses the Libav package to provide support for audio formats including MP3Ogg/Vorbis, and Windows Media Audio, and video formats such as DivXMPEG-2H.264WMV, and XviD. 


Q 2. What Is AVBin plugin?


Ans. AVBin Plugin is a special compiled library that provides us cross-platform support function API to perform various functions, necessary to play music files. In Other Words, You Just need to store only one point in your mind that This File Is Nessecery To Play A Music File Through Pyglet Library.


Q 3. Why I Select Pyglet Module To Play Music?

Ans. 

        Well Actually Features List Is Big But Here, I am writing only a few points



  • Simplicity
  • Cross-Platform Support
  • Object-Oriented Programming
  • Easy To Setup
  • Extra Extra.




So Our Pyglet Concept is Clear.



How it's Going To Work


Basically, I am just going to use pyglet module API to play music file Nothing Else. Because Pyglet library can handle other operation on its own so you don't need to worry about it.
To make our tutorial more interesting and useful, we going to create a class object loaded with all functionality of pyglet module to handle any music file in the simplest way. So, in future, you just need to import class object and use it play music.


Examples Codes To Play Music


Simplest Code:


# import module
import pyglet

# pass sound file path 
music = pyglet.resource.media('music.mp3')

# play sound
music.play()

# keep pyglet function alive
pyglet.app.run()

Well, Above codes are one the easiest piece of code to play any music files using pyglet. as you can see in above codes,


  • the first line is to import module,
  • the second line is to load music into pyglet handler,
  • the third line is to play music and
  • the last line is to keep running thread alive.


So, Now Let's Move to Next level codes

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#!/usr/bin/python

# Here Importing Modules
import pyglet     # import pyglet
import datetime   
import os
import time
import threading
import pyglet.media as media

# player
jump_distance=30



# ============================================
# Usages:
#       player=mediaplayer(path, song_time, song_duration, volume)
# Here:
#   path=String Variable For Song Path
#   song_time=String Variable For Song Playing Time
#   song_duration= String Variable For Time duration
#   volume = IntVar For Volume Updates
#
# For Other Functions:
#   player.YourFunction
# ============================================


class mediaplayer:
    def __init__(self, path, song_time,song_duration,volume):
        self.path=path                      # Song Playing Song
        self.volume=volume                  # Song Volume Update
        self.songtime=song_time             # Song Time Variable
        self.songduration=song_duration     # Song Duration
        self.player=media.Player()          # pyglet Media Player
        self.player.volume=1.5              # 
        self.time_thread()                  # Time Updating Thread

        self.path.trace('w',self.play_song)
        self.volume.trace('w', self.volume_)
        
    def jump(self, time):
        try:
            self.player.seek(time)
            return 
        except:
            print ('[+] Jump is Not Possible')
            return
        
        
    def now(self):
        storeobj=self.player.time
        return storeobj
    
    def now_(self):
        time=int(self.now())
        k=datetime.timedelta(seconds=time)
        k=k.__str__()
        return k

        
    def pause(self):
        self.player.pause()    
        return 

    def play(self):
        self.player.play()
        return
    
    def stop(self):
        self.reset_player()
        return
    
    def volume_(self, *args, **kwargs):
        try:
            volume=self.volume.get()
            self.player.volume=volume
        except:
            pass
        return
    
    def time_thread(self):
        threading.Thread(target=self.update_time_).start()
        return
    
        
    def update_time_(self):
        while True:
            now=self.now_()
            try:
                self.songtime.set(now)
                pass
            
            except Exception as e:
                print e
                pass
        
    
    def duration(self):
        try:
            storeobj=self.player.source.duration
            return storeobj
        except:
            return '0'
    def duration_(self):
        time=self.duration()+10.0
        k=datetime.timedelta(seconds=time)
        k=k.__str__()
        return k
    
    def reset_player(self):
        self.player.pause()
        self.player.delete()
        return
            
            
    
    def play_song(self, *args, **kwargs):
        if self.path.get():
            try:
                self.reset_player()
                try:
                    src=media.load(self.path.get())
                    self.player.queue(src)
                    self.play()
                    
                    self.songduration.set(self.duration_())   # Updating duration Time
                    return 
                except Exception as e:
                    print ("[+] Something wrong when playing song",e)
                    return 
            except Exception as e:
                print (' [+] Please Check Your File Path', self.path.get())
                print (' [+] Error: Problem On Playing \n ',e)
                return 
        else:
            print (' [+] Please Check Your File Path', self.path.get())
        return

    def fast_forward(self):
        time = self.player.time + jump_distance
        try:
            if self.duration() > time:
                self.player.seek(time)
            else:
                self.player.seek(self.duration())
        except AttributeError:
            pass

    def rewind(self):
        time = self.player.time - jump_distance
        try:
            self.player.seek(time)
        except:
            self.player.seek(0)

    


Simply To play Music with Above Class, You Just need to Type Below Codes at the bottom of the same script.



# Here:
#   path          = String Variable For Song Path
#   song_time     = String Variable For Song Playing Time
#   song_duration = String Variable For Time duration
#   volume        = IntVar For Volume Updates
#
#

# create class object
player=mediaplayer(path, song_time, song_duration, volume)

# play song
player.play_song()



Well, Friends From Here I am going to left further exercise to the reader. so that he/she can understand exactly what happens in these codes.





I hope you all enjoyed this Tutorial.
Please Don't forget to comment below
and provide your feedback.

Written By
                SSB

Share this

Related Posts

Previous
Next Post »