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:
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
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)
Hence, the audio file will be playing on your default music player once you try.
#random audio file will be played on default player
- 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.