How to play random mp3 from a folder in Python

This tutorial is about how to play random mp3 from a folder in Python. Python contains a lot of Predefined modules. Python has a module that is the random module by using the random module to play random mp3 from a folder. So keep reading it to see how we can do it…

The following are constrains to play an mp3 from a folder:

  • The mp3 audio folder path must be specified to open the mp3 audio on the computer.
  • By using random.choice() method to select a particular mp3 audio present in the folder.
  • All the mp3 audio must be stored in the .py file location to start the mp3 audio using the OS module otherwise you must change to mp3 audio folder location using change directory to play the mp3 audio.

Importing Random Module:

So, let us have a look at importing the random module:

import random

Importing random module in .py file

Importing OS Module:

So, let us have a look at importing the OS module:

import random
import os

Importing os module in .py file

Folder Details:

The folder contains a lot of mp3 audios by using random function a particular mp3 audio is selected and played by using OS module

#-----------------Inside the folder-----------
audio1.mp3
audio2.mp3
audio3.mp3

Example to play random mp3 from a folder:

import os
import random 
path="C:\\Users\\sairajesh\\Desktop\\audios"
files=os.listdir(path)
d=random.choice(files)
os.startfile(d)

output:

Hence, the audio file will be playing on your default music player once you try.

#random audio file will be played on default player

Explanation:

  • First, you select the path of the folder where the mp3 audios are present like->c\\user\\folder33
  • By using the listdir() method store all the files present in the folder
  • By using random.choice() method to select a particular mp3 audio and os.startfile() method to play the mp3 audio

OS.Start file() method:

The os.startfile() method will be used to run the file present in the folder directly on the default opener of the file. Here the mp3 audios file will be played on VLC player or media player, etc.

 

2 responses to “How to play random mp3 from a folder in Python”

  1. Gaurav Rajendra Borse says:

    there is some small change in your code that u specified above.
    there is error in last line “os.startfile(d)” as “Exception has occurred: FileNotFoundError
    [WinError 2] The system cannot find the file specified: ‘myfile.mp3′”
    solution for this –
    import os
    import random
    path=”F:\\Songs\\”
    files=os.listdir(path)
    d=random.choice(files)
    os.startfile(‘F:\\Songs\\’ + d)

Leave a Reply

Your email address will not be published. Required fields are marked *