Open In App

How Can I Play Music In Background In Python On Windows?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Playing music in the background can add a dynamic and engaging element to your Python projects on Windows. Whether you are working on a game, a GUI application, or a multimedia project, integrating background music can enhance the user experience. In this guide, we’ll explore how to play music in the background using Python on a Windows environment.

How Can I Play Music In Background In Python On Windows?

Below, is the step-by-step guide of How Can I Play Music In Background In Python On Windows. This Python script is a basic music player that allows users to play either a single song or all songs in a specified folder. Let’s break down the code into subparts and explain them in detail

Step 1: Create a Virtual Environment

First, create the virtual environment using the below commands

python -m venv env 
.\env\Scripts\activate.ps1

Step 2: Initialization and Setup

The script starts by importing necessary libraries, including os for file operations and pygame for handling audio. It initializes the Pygame mixer with specific parameters to improve audio playback.

Python3




import os
import pygame
import random
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
pygame.mixer.init()


Step 3: Music Playback Functions

These functions define basic music playback operations using the Pygame mixer. play_music loads and plays a given music file, while pause_music, unpause_music, and stop_music handle pausing, resuming, and stopping the music, respectively.

Python3




def play_music(file_path):
    pygame.mixer.music.load(file_path)
    pygame.mixer.music.play()
 
def pause_music():
    pygame.mixer.music.pause()
 
def unpause_music():
    pygame.mixer.music.unpause()
 
def stop_music():
    pygame.mixer.music.stop()


Step 4: Playing a Single Song

The play_single_song function prompts the user to enter the name of a specific song file within a provided folder. It then allows the user to control the playback with commands such as pause, resume, stop, and toggle loop.

Python3




def play_single_song(folder_path):
    # (...)


Step 5: Playing All Songs in a Folder

The play_all_songs_in_folder function retrieves all audio files with recognized extensions from a specified folder. It provides a menu for users to control playback, including options for looping, shuffling, and moving between songs.

Python3




def play_all_songs_in_folder(folder_path):
    # (...)


Step 6: Main Execution Block

The script’s main execution block prompts the user to choose between playing a single song or all songs in a folder. It then calls the appropriate function based on the user’s choice.

Python3




if __name__ == "__main__":
    pygame.mixer.init()
    choice = input("Enter 's' to play a single song, 'f' to play all songs in a folder: ")
    if choice.lower() == 's':
        # (...)
    elif choice.lower() == 'f':
        # (...)
    else:
        print("Invalid choice.")


Complete Code

Python3




import os
import pygame
import random
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
pygame.mixer.init()
 
def play_music(file_path):
    pygame.mixer.music.load(file_path)
    pygame.mixer.music.play()
 
def pause_music():
    pygame.mixer.music.pause()
 
def unpause_music():
    pygame.mixer.music.unpause()
 
def stop_music():
    pygame.mixer.music.stop()
 
def play_single_song(folder_path):
    song_name = input("Enter the name of the song you want to play (include the file extension): ")
    file_path = os.path.join(folder_path, song_name)
    if os.path.exists(file_path):
        print(f"Playing: {song_name}")
        play_music(file_path)
        while True:
            command = input("Type 'p' to pause, 'r' to resume, 's' to stop, 'l' to toggle loop, "
                            "'sh' to toggle shuffle, 'e' to exit: ")
            if command.lower() == 'p':
                pause_music()
            elif command.lower() == 'r':
                unpause_music()
            elif command.lower() == 's':
                stop_music()
                print("Song stopped.")
                break
            elif command.lower() == 'l':
                pygame.mixer.music.set_endevent(pygame.USEREVENT)
                loop = not pygame.mixer.music.get_endevent()  # Toggle loop
                pygame.mixer.music.set_endevent(pygame.USEREVENT if loop else None)
                print(f"Loop {'enabled' if loop else 'disabled'}.")
            elif command.lower() == 'sh':
                print("Cannot shuffle in single-song mode.")
            elif command.lower() == 'e':
                stop_music()
                break
            else:
                print("Invalid command.")
    else:
        print(f"Song '{song_name}' not found in the folder.")
 
def play_all_songs_in_folder(folder_path):
    audio_extensions = ['.mp3', '.wav', '.ogg', '.flac']
    files = [file for file in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, file)) and
             os.path.splitext(file)[1].lower() in audio_extensions]
    current_song_index = 0
    loop = False
    shuffle = False
 
    while True:
        file_path = os.path.join(folder_path, files[current_song_index])
        print(f"Playing: {files[current_song_index]}")
        play_music(file_path)
        while True:
            for event in pygame.event.get():
                if event.type == pygame.USEREVENT and loop:
                    play_music(file_path)
                elif event.type == pygame.USEREVENT and not loop:
                    current_song_index = (current_song_index + 1) % len(files)
                    file_path = os.path.join(folder_path, files[current_song_index])
                    play_music(file_path)
            command = input("Type 'p' to pause, 'r' to resume, 'n' to play the next song, "
                            "'b' to play the previous song, 's' to stop, 'l' to toggle loop, "
                            "'sh' to toggle shuffle, 'e' to exit: ")
            if command.lower() == 'p':
                pause_music()
            elif command.lower() == 'r':
                unpause_music()
            elif command.lower() == 'n':
                current_song_index = (current_song_index + 1) % len(files)
                break
            elif command.lower() == 'b':
                current_song_index = (current_song_index - 1) % len(files)
                break
            elif command.lower() == 's':
                stop_music()
                print("Song stopped.")
                return
            elif command.lower() == 'l':
                loop = not loop
                pygame.mixer.music.set_endevent(pygame.USEREVENT if loop else None)
                print(f"Loop {'enabled' if loop else 'disabled'}.")
            elif command.lower() == 'sh':
                shuffle = not shuffle
                if shuffle:
                    random.shuffle(files)
                    print("Playlist shuffled.")
                else:
                    files.sort()
                    print("Playlist unshuffled.")
            elif command.lower() == 'e':
                stop_music()
                return
            else:
                print("Invalid command.")
 
if __name__ == "__main__":
    pygame.mixer.init()
    choice = input("Enter 's' to play a single song, 'f' to play all songs in a folder: ")
    if choice.lower() == 's':
        folder_path = input("Enter the folder path where the song is located: ")
        play_single_song(folder_path)
    elif choice.lower() == 'f':
        folder_path = input("Enter the folder path where the songs are located: ")
        play_all_songs_in_folder(folder_path)
    else:
        print("Invalid choice.")


Run the Server

python script_name.py

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads