You are on page 1of 22

Music Player Application in Python

using Tkinter and Pygame module

Report submitted to
Guru Jambheshwar university of science and technology, Hisar
For the award of the degree

Of

Bachelor of Technology
In Information Technology

by
SRIJAN GUPTA
190010140058

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

1
DECLARATION

I certify that
a. The work in this report is original and has been done by me under
the udemy instructor.
b. I have followed the guidelines provided by the institute in preparing
the report.
c. I have confirmed to the norms and guidelines given in the Ethical
code of conduct of the institute.
d. Whenever I have used materials (data, theoretical analysis, figures,
and text) from other sources, I have given due credit to them by
citing them in the text of the report and giving their details in the
references. Further, I have taken permission from the copyright
owners of the sources, whenever necessary.

Signature of Student

2
CERTIFICATE

This is to certify that the dissertation Report entitled, “Music Player


Application in Python using Tkinter and Pygame module.” submitted by
Miss. “Srijan Gupta” to Guru Jambheshwar University of Science &
Technology, Hisar, India, is a record of bona-fide project work carried out
by him under my supervision and guidance and is worthy of consideration
for the award of the degree of Bachelor of Technology in Information
Technology of the Institute.

Mr. Amit Malik Mr.


Dharmendra Kumar
Supervisor Head of the
Department

Date: 11 January, 2023

Abstract
3
In our daily life we see every next person have hobby of listening to
music. But as we know that the audio files are digital files. Therefore,
there is a need of a tool to run the digital files or in other words, play the
files. Thus, we need MP3 players. It is a device using to play MP3s and
other digital audio files.
This program will allow to play songs, music, and all MP3 files on desktop
or laptops. MP3 player using Python is a basic programming application
built using the programming language Python. It is a GUI program built by
the means of Python libraries Tkinter, Pygame and Mutagen.

4
CONTENTS
Cover Page 1

Declaration 2

Certificate by the Supervisor 3

Abstract 4

Chapter 1 Introduction to GUI applications 6

Chapter 2 Python 8

Chapter 3 All about Tkinter 11

Chapter 4 Fundamentals of Pygame 12

Chapter 5 OS module 14

Project 17

Conclusion 25

5
1.Introduction to GUI Applications

GUI stands for Graphical User Interface.

A graphical user interface (GUI) is a type of user interface through which


users interact with electronic devices via visual indicator representations.
Common examples of GUI is Microsoft operating systems, apple macos.

What are the elements of a GUI?

 Button - A graphical representation of a button that performs an


action in a program when pressed
 Dialog box - A type of window that displays additional information,
and asks a user for input.
 Icon - Small graphical representation of a program, feature, or file.
 Menu - List of commands or choices offered to the user through the
menu bar.
 Menu bar - Thin, horizontal bar containing the labels of menus.
 Ribbon - Replacement for the file menu and toolbar that groups
programs activities together.
 Tab - Clickable area at the top of a window that shows another page
or area.
 Toolbar - Row of buttons, often near the top of an application
window, that controls software functions.
 Window - Rectangular section of the computer's display that shows
the program currently being used.

Advantages of GUI

1. This type of user interface is easy to use, especially for a


beginners.

2. It is easy to explore and find your way around the system using a
WIMP/ GUI interface.

3. You do not have to learn complicated commands.

6
4. There are usually a reasonable 'help' system included with WIMP
interface.

5. They let you exchange data between different software


applications.

Disadvantages of GUI

1. GUIs take up a much larger amount of hard disk space than other
interfaces.

2. They need significantly more memory (RAM) to run than other


interface types.

3. They use more processing power than other types of interface.

4. They can be slow for experienced programmers to use. These


people often find CLI interfaces much faster to use.

2.PYTHON
Python is a general purpose, dynamic, high-level, and interpreted
programming language. It supports Object Oriented programming
approach to develop applications. It is simple and easy to learn
and provides lots of high-level data structures.

Where is python used ?

o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
7
Python Basic Syntax

def func():
statement 1
statement 2
…………………
…………………
statement N

Python popular Framework and Libraries

o Web development (Server-side) - Django Flask, Pyramid,


CherryPy
o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn,
Matplotlib, Scipy, etc.
o Mathematics - Numpy, Pandas, etc

Python variables

Python has five standard data types −

 Numbers- Number data types store numeric values.


 String- Strings in Python are identified as a contiguous set of
characters represented in the quotation marks.
 List- A list contains items separated by commas and enclosed within
square brackets ([]).
 Tuple- A tuple is another sequence data type that is similar to the
list.
 Dictionary- Dictionaries are type of hash table type. Dictionaries are
enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).

8
Types of Operator

Python language supports the following types of operators.

 Arithmetic Operators-(+ ,- ,*, /, %, **,//)


 Comparison (Relational) Operators-(==,!=,<>,<=,>=,<,>)
 Assignment Operators-(=,+=,-=,*=,%=)
 Logical Operators-(and,or,xor^,<<,>>)
 Membership Operators-(in,not in)
 Identity Operators-(is,is not)

Loops

while loop

Repeats a statement or group of statements while a given condition is


TRUE. It tests the condition before executing the loop body.

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i

for loop
Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

9
nested loops
You can use one or more loop inside any another while, for or do..while
loop.

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)

Python functions

A function is a block of code which only runs when it is called.

def my_function(country = "Norway"):


print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

10
print(p1.name)
print(p1.age)

Python Iterators

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit)

Exception Handling

When an error occurs, or exception as we call it, Python will normally


stop and generate an error message.

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try-
and except blocks.

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Finally:

The finally block, if specified, will be executed regardless if the try block
raises an error or not.
11
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

3 All About Tkinter

Python provides the standard library Tkinter for creating the


graphical user interface for desktop based applications.

An empty Tkinter top-level window can be created by using the following


steps.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the
user's computer screen.

from tkinter import *


top = Tk()
top.mainloop()

Tkinter widgets

There are various widgets like button, canvas, checkbutton, entry, etc. that
are used to build the python GUI applications.

1.Button

12
The Button is used to add various kinds of buttons to the python
application.

2.canvas

The Canvas widget is used to draw shapes, such as lines, ovals, polygons
and rectangles, in your application

3.Checkbutton
The Checkbutton widget is used to display a number of options as
checkboxes. The user can select multiple options at a time.
4. Entry
The Entry widget is used to display a single-line text field for accepting
values from a user.
5. Frame
The Frame widget is used as a container widget to organize other widgets
6. Label
The Label widget is used to provide a single-line caption for other
widgets. It can also contain image.
7. Listbox

The Listbox widget is used to provide a list of options to a user.

8. Menubutton

The Menubutton widget is used to display menus in your application.

9. Menu
The Menu widget is used to provide various commands to a user. These
commands are contained inside Menubutton
10. Message
The Message widget is used to display multiline text fields for accepting
values from a user

13
Python Tkinter pack() method

The pack() widget is used to organize widget in the block.

widget.pack(options)

Python Tkinter grid() method

The grid() geometry manager organizes the widgets in the tabular form.

widget.grid(options)

Python Tkinter place() method

The place() geometry manager organizes the widgets to the specific x and
y coordinates.

widget.place(options)

Syntax

from tkinter import*


top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()

14
4.Fundamentals of Pygame

~ Pygame is a Python module that works with computer


graphics and sound libraries and designed with the power of
playing with different multimedia formats like audio,
video,etc.

o Pygame is a cross-platform set of Python modules which is used to


create video games.
o It consists of computer graphics and sound libraries designed to be
used with the Python programming language.
o Pygame was officially written by Pete Shinners to replace PySDL.
o Pygame is suitable to create client-side applications that can be
potentially wrapped in a standalone executable.

Installation through PIP:

py -m pip install -U pygame --user

Simple pygame Example:

import pygame
pygame.init()
screen = pygame.display.set_mode((400,500))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()

15
import pygame - This provides access to the pygame framework and
imports all functions of pygame.

pygame.init() - This is used to initialize all the required module of the


pygame.

pygame.display.set_mode((width, height)) - This is used to display a


window of the desired size. The return value is a Surface object which is
the object where we will perform graphical operations.

pygame.event.get()- This is used to empty the event queue. If we do not


call this, the window messages will start to pile up and, the game will
become unresponsive in the opinion of the operating system.

pygame.QUIT - This is used to terminate the event when we click on the


close button at the corner of the window.

pygame.display.flip() - Pygame is double-buffered, so this shifts the


buffers. It is essential to call this function in order to make any updates
that you make on the game screen to make visible.

5.OS Module

This module provides different functions for interaction with the


Operating System.

To work with the OS module, we need to import the OS module.


import os

os.name()

This function provides the name of the operating system module that it
imports.

os.mkdir()

The os.mkdir() function is used to create new directory. Consider the


following example.
16
os.getcwd()

It returns the current working directory(CWD) of the file.

os.chdir()

The os module provides the chdir() function to change the current


working directory.

os.rmdir()

The rmdir() function removes the specified directory with an absolute or


related path. First, we have to change the current working directory and
remove the folder.

os.error()

The os.error() function defines the OS level errors. It raises OSError in


case of invalid or inaccessible file names and path etc.

os.popen()

This function opens a file or from the command specified, and it returns a
file object which is connected to a pipe

os.close()

This function closes the associated file with descriptor fr.

os.rename()

A file or directory can be renamed by using the function os.rename(). A


user can rename the file if it has privilege to change the file

os.access()

This function uses real uid/gid to test if the invoking user has access to
the path.

17
6 PROJECT

Language Used :- Python

import os
from tkinter.filedialog import askdirectory
import pygame
from mutagen.id3 import ID3
from tkinter import*
root= Tk()
root.minsize(600,600)
listofsongs=[]
realnames=[]
v= StringVar()
songlabel= Label(root, textvariable=v,width=35)
index = 0
def nextsong(event):
global index
index += 1
pygame.mixer.music.load(listofsongs[index])
pygame.mixer.music.play()
updatelabel()
def prevsong(event):
global index
index -= 1
pygame.mixer.music.load(listofsongs[index])

18
pygame.mixer.music.play()
updatelabel()
def stopsong(event):
pygame.mixer.music.stop()
v.set(" ")
def updatelabel():
global index
#global songname
v.set(listofsongs[index])
#return songname
def directorychooser():
directory = askdirectory()
os.chdir(directory)
for files in os.listdir(directory):
if files.endswith(".mp3"):
realdir=os.path.realpath(files)
audio=ID3(realdir)
#realnames.append(audio['TIT2'].text[0])
listofsongs.append(files)
pygame.mixer.init()
pygame.mixer.music.load(listofsongs[0])
pygame.mixer.music.play()
directorychooser()
Label=Label(root,text="Srijan's music player")
Label.pack()
listbox = Listbox(root)

19
listbox.pack()
for items in listofsongs:
listbox.insert(0,items)
nextbutton=Button(root, text="next song")
nextbutton.pack()
previousbutton=Button(root, text="previous song")
previousbutton.pack()
stopbutton=Button(root, text="stop song")
stopbutton.pack()
nextbutton.bind("<Button-1>", nextsong)
previousbutton.bind("<Button-1>", prevsong)
stopbutton.bind("<Button-1>", stopsong)
songlabel.pack()
root.mainloop()

20
CONCLUSION
This project has really been a good start and informative. It has made us
understand and learn how things go on frontend.
The scope of this project is to polish our skills, entertainment purpose and
to accomplish good grades .

References
https://www.w3schools.com/
https://blog.openclassrooms.com/
https://www.javatpoint.com/

21
22

You might also like