Music Player using Python and Streamlit


Introduction:

This project shows you how to create a basic music player web application using Python and Streamlit. You’ll learn how to list music files from a directory, allow users to select a file, and play it directly in the app.

Project Prerequisites:

  • Python: Ensure Python is installed on your system. Download from the official website: Python Official Website
  • Streamlit: Install the Streamlit library:
pip install streamlit
  • Music Files: Place some music files (MP3, WAV, OGG) in a folder named music in the same directory as your Python script.

Getting Started:
Step 1: Set Up Your Music Files
Create a folder named music in the same directory where you'll save your Python script. Place your music files (.mp3.wav.ogg) inside this folder.

Step 2: Create a New Python Script
Open your text editor or IDE and create a new Python file (e.g., music_player.py).

Step 3: Write the Code
Copy and paste the following code into your script:

import streamlit as st
import os
st.title("Music Player")
# Directory containing music files
music_dir = "./music"
# Get a list of music files
music_files = [f for f in os.listdir(music_dir) if f.endswith((".mp3", ".wav", ".ogg"))]
# Select music file
selected_file = st.selectbox("Select a music file", music_files)
# Play music
if selected_file:
audio_file = open(os.path.join(music_dir, selected_file), "rb")
audio_bytes = audio_file.read()
st.audio(audio_bytes, format="audio/ogg") # Adjust format as needed

Step 4: Run the Application
Save the script. In your terminal, navigate to the directory where you saved the file and run:

streamlit run music_player.py

Step 5: Use the Music Player
The music player app will open in your browser. You’ll see a dropdown menu to select a music file from your music folder. Choose a file, and it will start playing in the app.

Guide:

  • st.title(): Sets the title of your app.
  • music_dir: Specifies the directory where your music files are located.
  • os.listdir(): Gets a list of all files and directories in the music_dir.
  • endswith(): Filters the list to include only files with the specified extensions (.mp3.wav.ogg).
  • st.selectbox(): Creates a dropdown menu to select a music file.
  • st.audio(): Plays the selected audio file in the app.
  • The format argument should match the actual format of your audio file. You might need to change it to "audio/mp3" or "audio/wav" depending on your files.

This is a basic music player. You can enhance it further by:

  • Adding a play/pause button: Use Streamlit buttons and session state to control playback.
  • Creating a playlist: Allow users to select multiple songs and create a playlist.
  • Adding a volume control: Use a slider to adjust the volume.
  • Displaying song information: Show the song title, artist, and album art (if available).
  • Using a more advanced audio library: Explore libraries like pygame for more control over audio playback and features.

Advertisement