DevelopmentNovember 01, 20243 min read

Music Player using Python and Streamlit

Create a music player web app with Python and Streamlit — browse your local library, play MP3s, and control playback in the browser.

Galvan

Galvan

Founder & Creator

Introduction

This project shows you how to build a Music Player web app using Python and Streamlit. The app scans a local folder for audio files, lets users pick a track from a dropdown, and plays it using the browser's native audio player. For the video counterpart, see the Streamlit video player; for generated audio, the gTTS text-to-speech app.


> 🎬 Watch the Full Video Tutorial:

> Watch the walkthrough on YouTube: TOP Python PRO Shares Music Player SECRETS Using Streamlit


Prerequisites

  • Python 3.8+python.org
  • Streamlit:
  • code
    pip install streamlit
  • Music Files — Place .mp3, .wav, or .ogg files in a folder called music/ next to your script.
  • Project Structure

    code
    music_player/
    ├── music_player.py
    └── music/
        ├── track1.mp3
        ├── track2.mp3
        └── track3.wav

    Step 1: Set Up Your Music Folder

    Create a folder called music in the same directory as your script and drop your audio files inside it.

    Step 2: Create the Script

    Create music_player.py and paste the following:

    code
    import streamlit as st
    import os
    
    st.set_page_config(page_title="Music Player", page_icon="🎵")
    st.title("🎵 Music Player")
    
    MUSIC_DIR = "./music"
    SUPPORTED = (".mp3", ".wav", ".ogg", ".flac")
    
    if not os.path.exists(MUSIC_DIR):
        st.error("Music folder not found. Create a 'music/' folder and add audio files.")
        st.stop()
    
    files = sorted([f for f in os.listdir(MUSIC_DIR) if f.lower().endswith(SUPPORTED)])
    
    if not files:
        st.warning("No audio files found. Add .mp3, .wav, or .ogg files to the music/ folder.")
        st.stop()
    
    st.write(f"**{len(files)} track(s) available**")
    selected = st.selectbox("🎧 Choose a track:", files)
    
    if selected:
        path = os.path.join(MUSIC_DIR, selected)
        name = os.path.splitext(selected)[0]
        size_mb = os.path.getsize(path) / (1024 * 1024)
        ext = selected.rsplit(".", 1)[-1].lower()
    
        st.subheader(f"▶️ Now Playing: {name}")
        col1, col2 = st.columns([3, 1])
        with col1:
            with open(path, "rb") as f:
                st.audio(f.read(), format=f"audio/{ext}")
        with col2:
            st.metric("Size", f"{size_mb:.1f} MB")
            st.metric("Format", ext.upper())

    Step 3: Run the App

    code
    streamlit run music_player.py

    Step 4: Use the Player

    Select a track from the dropdown and it will load instantly in the browser's native audio player — with play, pause, seek, and volume controls.

    How It Works

    The player scans a local music/ folder with os.listdir (filtered by extension), builds a track list, and renders it in an st.selectbox. Choosing a track reads the file as bytes and hands them to st.audio(), which renders the browser's native audio element with seek controls — supporting MP3, WAV, and OGG.

    The interesting part is session state: st.session_state["current_track"] remembers the selection across reruns, so the player does not reset when you toggle other widgets. This is the same pattern the quiz app uses to track the current question.

    Extra touches like an auto-play toggle or a simple volume slider map to st.audio parameters and st.slider — the app stays under 100 lines while feeling like a real player.

    Key Concepts

  • `os.listdir()` — Lists all files in the music directory.
  • `endswith(SUPPORTED)` — Filters the list to supported audio formats.
  • `st.selectbox()` — Renders the track-selection dropdown.
  • `st.audio()` — Embeds the native HTML5 audio player.
  • What to Try Next

  • Show album art if a matching .jpg exists in the music folder.
  • Build a playlist queue using st.session_state.
  • Add a shuffle button that picks a random track automatically.
  • Common Errors & Fixes

  • `FileNotFoundError` after adding songs — the app scanned the folder at startup only. Re-run the scan on each rerun or add a refresh button.
  • Track plays but seek bar is broken — variable-bit-rate MP3s confuse browser duration calculation; re-encode with constant bit rate.
  • `st.audio` shows a broken player — you passed a path where bytes were expected (or vice versa); both work, but be consistent.
  • Selection resets on every click — the track choice is not persisted; write it to st.session_state inside the selectbox callback.
  • Folder scan misses songs in subfoldersos.listdir is not recursive; use pathlib.Path("music").rglob("*.mp3") to include nested folders.
  • FAQ

    Which audio formats are supported?

    Whatever the browser plays natively: MP3 and WAV everywhere, OGG in most. FLAC support depends on the browser.

    Can I stream from a URL?

    Yes — st.audio accepts a URL string, so you can point at hosted files or an icecast stream.

    How do I add a playlist queue?

    Use a multiselect of tracks stored in st.session_state and advance an index on track end — the state pattern is identical to the quiz app.