Play Random MP3 from a Folder in Python

Before, implement check the music folder.

Copyright free Music

Step 1: Import Necessary Libraries

First, we need to import the necessary libraries. The os library will help us navigate the file system, random will help us select a random file, and Pygame will handle the audio playback.

Python
import os
import random
import pygame

Step 2: Initialize Pygame Mixer

Pygame’s mixer module is used for loading and playing sounds. We need to initialize it before we can use it.

Python
pygame.mixer.init()

Step 3: Define the Folder Path

Next, specify the path to the folder containing your MP3 files. Make sure this path is correct and points to the directory where your MP3 files are stored.

Python
folder_path = 'path/to/your/mp3/folder'

Step 4: List All MP3 Files in the Folder

We will use the os.listdir method to list all files in the specified folder and filter out the MP3 files.

Python
mp3_files = [file for file in os.listdir(folder_path) if file.endswith('.mp3')]

Step 5: Select a Random MP3 File

Using the random.choice method, we can select a random MP3 file from our list.

Python
random_mp3 = random.choice(mp3_files)

Step 6: Play the Selected MP3 File

Now, we will use Pygame to load and play the selected MP3 file. We need to construct the full path to the file and then load and play it using Pygame’s mixer module.

Python
file_path = os.path.join(folder_path, random_mp3)
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()

Step 7: Keep the Script Running Until the Music Ends

To ensure the script doesn’t terminate before the music finishes playing, we will add a loop that checks if the music is still playing.

Python
while pygame.mixer.music.getbusy():
    pygame.time.Clock().tick(10)

Output:

Conclusion

So, finally we created a Python script that randomly selects and plays an MP3 file from a specified folder. This script can be further enhanced by adding features such as GUI interfaces, playlists, or additional controls for playback.


How to Play Random mp3 from a Folder in Python

Playing a random MP3 file from a folder using Python is an exciting and practical task that combines file handling, randomness, and multimedia libraries. In the tutorial, we’ll create a simple script that randomly selects and plays an MP3 file from a specified folder.

Similar Reads

Play Random MP3 from a Folder in Python

Before, implement check the music folder....