Open In App

How to Close MP3 Files Using Python?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Manipulating audio files, such as MP3s, is a common task in Python programming, especially in applications involving audio processing, music players, or audio analysis. This article will explore concepts related to this topic and guide how to effectively close MP3 files in Python.

Closing MP3 files Using Python

Below, are the code examples of how to close mp3 files that are being used by Python:

File Structure

op

Example 1: Close MP3 Files Using Pygame

Let’s consider a simple example where we open an MP3 file, play it, and then close it using the pygame library, which provides functionalities for multimedia applications in Python. we can install the pygame library using the following command.

pip install pygame 

In this example, below code code employs Pygame to play an MP3 file. It initializes the mixer, loads the MP3, plays it, waits for user input to stop, and then halts playback. The function is exemplified using an MP3 file named “example.mp3”.

Python3
import pygame

def play_mp3(file_path):
    pygame.mixer.init()
    pygame.mixer.music.load(file_path)
    pygame.mixer.music.play()
    input("Press Enter to stop playback...")
    pygame.mixer.music.stop()

# Example usage
mp3_file = "example.mp3"
play_mp3(mp3_file)

Output

Hello from the pygame community. https://www.pygame.org/contribute.html
Press Enter to stop playback...

Example 2: Close MP3 Files That Are Being Used Using Pynput

For the second method, we’ll explore an alternative approach to playing and stopping MP3 files in Python using the multiprocessing module and the pynput library. Before diving into the code, ensure you have the playsound library installed in your Python environment, which can be done using the following command:

pip install pynput

In this example, below code uses multiprocessing to play an MP3 file concurrently while monitoring keyboard events using the pynput library. It defines functions to play the sound and terminate the process upon keypress, ensuring smooth interaction. Upon execution, it starts the sound process and listens for keyboard input, allowing the user to stop playback.

Python3
import multiprocessing
from playsound import playsound
from pynput import keyboard

def play_sound(file_path):
    playsound(file_path)

def on_press(key):
    if p.is_alive():
        p.terminate()
        print("Sound stopped.")
        exit(0)

if __name__ == '__main__':
    p = multiprocessing.Process(target=play_sound, args=("example.mp3",))
    p.start()

    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()

Output

Sound stopped

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads