w3resource

Basic Music Player Project: Tkinter vs PyQt5 Solutions for Python


Basic Music Player:

Build a simple music player that plays local audio files.

Input values:
User interacts with the music player by selecting audio files to play, controlling playback (play, pause, stop), and adjusting volume.

Output value:
Audio files are played with a visual representation of playback controls and volume adjustments.

Example:

Input values:
1. Select the audio file: "song1.mp3"
2. Click the play button
Output value:
Music player displays playback controls and starts playing "song1.mp3".
Input values:
3. Pause playback
Output value:
Music player pauses playback at the current position.
Input values:
4. Select the audio file: "song2.mp3"
5. Click the play button
Output value:
Music player displays playback controls and starts playing "song2.mp3".
Input values:
6. Stop playback
Output value:
Music player stops playback, and the playback position resets.
Input values:
7. Adjust the volume to 75%
Output value:
Music player adjusts the volume to 75%. 

Here are two different solutions for building a "Basic Music Player" in Python. The music player will allow users to select audio files, control playback (play, pause, stop), and adjust volume.

Solution 1: Using Tkinter and Pygame

Code:

 # Solution 1: Basic Music Player Using Tkinter and Pygame

import tkinter as tk  # Import tkinter for GUI
from tkinter import filedialog  # Import filedialog to open file selection dialog
from pygame import mixer  # Import mixer module from pygame for audio playback

class MusicPlayer:
    """Class to create a simple music player with Tkinter and Pygame."""

    def __init__(self, root):
        """Initialize the MusicPlayer with a Tkinter root window."""
        self.root = root
        self.root.title("Basic Music Player")
        self.root.geometry("300x200")

        # Initialize Pygame mixer
        mixer.init()

        # Set up GUI elements
        self.setup_ui()

        # Initialize playback state
        self.current_file = None
        self.paused = False

    def setup_ui(self):
        """Set up the user interface with buttons and a volume slider."""
        # Button to open an audio file
        self.open_btn = tk.Button(self.root, text="Open", command=self.open_file)
        self.open_btn.pack(pady=5)

        # Button to play the audio
        self.play_btn = tk.Button(self.root, text="Play", command=self.play_music)
        self.play_btn.pack(pady=5)

        # Button to pause the audio
        self.pause_btn = tk.Button(self.root, text="Pause", command=self.pause_music)
        self.pause_btn.pack(pady=5)

        # Button to stop the audio
        self.stop_btn = tk.Button(self.root, text="Stop", command=self.stop_music)
        self.stop_btn.pack(pady=5)

        # Volume slider to adjust volume
        self.volume_slider = tk.Scale(self.root, from_=0, to=100, orient="horizontal", command=self.set_volume)
        self.volume_slider.set(50)  # Set initial volume to 50%
        self.volume_slider.pack(pady=5)

    def open_file(self):
        """Open a file selection dialog to select an audio file."""
        self.current_file = filedialog.askopenfilename(filetypes=[("Audio Files", "*.mp3 *.wav *.ogg")])

    def play_music(self):
        """Play the selected audio file."""
        if self.current_file:
            if self.paused:
                mixer.music.unpause()  # Resume playing if paused
                self.paused = False
            else:
                mixer.music.load(self.current_file)  # Load the selected file
                mixer.music.play()  # Start playing

    def pause_music(self):
        """Pause the audio playback."""
        if not self.paused:
            mixer.music.pause()  # Pause the playback
            self.paused = True

    def stop_music(self):
        """Stop the audio playback."""
        mixer.music.stop()  # Stop the playback

    def set_volume(self, value):
        """Set the volume of the audio playback."""
        volume = int(value) / 100  # Convert slider value to a float between 0 and 1
        mixer.music.set_volume(volume)

# Create a Tkinter window
root = tk.Tk()
# Create an instance of the MusicPlayer class
player = MusicPlayer(root)
# Start the Tkinter event loop
root.mainloop() 

Output:

Python: Basic Music Player.

Explanation:

  • Tkinter GUI:
    • Tkinter is used to create a simple user interface with buttons (Open, Play, Pause, Stop) and a volume slider.
  • Pygame Mixer:
    • Pygame's mixer module is initialized to handle audio playback.
    • open_file(): Allows the user to select an audio file.
    • play_music(): Plays or resumes the selected audio file.
    • pause_music(): Pauses the currently playing audio.
    • stop_music(): Stops the audio and resets playback.
    • set_volume(): Adjusts the volume using the slider value.
  • Advantages: Lightweight and simple to use, easy to implement and understand, uses a familiar GUI library.

Solution 2: Using PyQt5

Code:

# Solution 2: Basic Music Player Using PyQt5 with Buttons at the Bottom

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QSlider, QFileDialog, QVBoxLayout, QWidget, QSpacerItem, QSizePolicy
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtCore import Qt, QUrl

class MusicPlayer(QMainWindow):
    """Class to create a simple music player with PyQt5."""

    def __init__(self):
        """Initialize the MusicPlayer with a PyQt5 main window."""
        super().__init__()
        self.setWindowTitle("Basic Music Player")
        self.setGeometry(100, 100, 300, 400)

        # Initialize the media player
        self.media_player = QMediaPlayer()

        # Set up the user interface
        self.setup_ui()

    def setup_ui(self):
        """Set up the user interface with buttons and a volume slider."""
        # Main widget and layout
        main_widget = QWidget()
        main_layout = QVBoxLayout()

        # Spacer item to push buttons to the bottom
        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        main_layout.addItem(spacer)

        # Layout for buttons at the bottom
        button_layout = QVBoxLayout()

        # Open button
        open_btn = QPushButton("Open")
        open_btn.clicked.connect(self.open_file)
        button_layout.addWidget(open_btn)

        # Play button
        play_btn = QPushButton("Play")
        play_btn.clicked.connect(self.media_player.play)
        button_layout.addWidget(play_btn)

        # Pause button
        pause_btn = QPushButton("Pause")
        pause_btn.clicked.connect(self.media_player.pause)
        button_layout.addWidget(pause_btn)

        # Stop button
        stop_btn = QPushButton("Stop")
        stop_btn.clicked.connect(self.media_player.stop)
        button_layout.addWidget(stop_btn)

        # Volume slider
        volume_slider = QSlider(Qt.Horizontal)
        volume_slider.setRange(0, 100)
        volume_slider.setValue(50)
        volume_slider.valueChanged.connect(self.set_volume)
        button_layout.addWidget(volume_slider)

        # Add button layout to the main layout
        main_layout.addLayout(button_layout)

        # Set the main layout to the central widget
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

    def open_file(self):
        """Open a file dialog to select an audio file."""
        file_path, _ = QFileDialog.getOpenFileName(self, "Open Audio File", "", "Audio Files (*.mp3 *.wav *.ogg)")
        if file_path:
            self.media_player.setMedia(QMediaContent(QUrl.fromLocalFile(file_path)))

    def set_volume(self, value):
        """Set the volume of the audio playback."""
        self.media_player.setVolume(value)

# Run the PyQt5 application
app = QApplication([])
window = MusicPlayer()
window.show()
app.exec_() 

Output:

Python: Basic Music Player Tkinter and Pygame using Pyqt5.

Explanation:

  • Main Layout (main_layout):
    • This layout is created to hold the main content of the window.
    • A spacer (QSpacerItem) is added at the top to push the button layout to the bottom.
  • Button Layout (button_layout):
    • A QVBoxLayout is used to align all buttons and the volume slider vertically.
    • All buttons (Open, Play, Pause, Stop) and the volume slider are added to this layout.
  • Adding the Button Layout:
    • The button_layout is added to the main_layout at the bottom.
  • Widget Configuration:
    • The main widget (main_widget) is set as the central widget of the main window.

Summary of Differences:

  • Solution 1: Using Tkinter and Pygame
    • Lightweight: Simple and easy to implement with basic GUI controls.
    • Audio Handling: Uses Pygame for audio playback.
    • Use Case: Suitable for small and simple applications with basic needs.
  • Solution 2: Using PyQt5
    • Advanced GUI: Provides a modern interface with PyQt5's features.
    • Built-in Multimedia Support: Utilizes PyQt5's native multimedia capabilities (QMediaPlayer).
    • Use Case: Better suited for more advanced applications requiring richer UIs and more features.

Both solutions provide a functional music player, but Solution 2 is more flexible and visually appealing, while Solution 1 offers a straightforward, minimal implementation.



Follow us on Facebook and Twitter for latest update.