pythonpygamebackground-music

Python: Playing a music playlist in the background using a different file


I am currently trying to use two Python files to create a learning game. I am wanting to incorporate background music for the learner to be able to concentrate, so I am wanting a music player to play a list of songs that would be preloaded. Below is the first file for the music player:

#Musicplayer File

import os
import pygame
import random

def play():
    #Get list from directory
    musicList = ['song1','song2','song3']

    random.shuffle(musicList)
    print(musicList)

    #Create music player
    pygame.mixer.init()
    pygame.mixer.music.load(musicList[0])
    print('Now playing: '+musicList[0])
    pygame.mixer.music.play()
    musicList.pop(0)
    songs = True

    while songs:
        if not pygame.mixer.music.get_busy():
            if len(musicList) == 0:
                print('Playlist has ended.')
                songs=False
            else:
                pygame.mixer.music.load(musicList[0])  
                print('Now playing: '+musicList[0])
                pygame.mixer.music.play()
                musicList.pop(0)

And I am wanting to play it in the background of my second file:

import Musicplayer

#Play music player in the background
Musicplayer.play()

ans1 = 2
print('What is 1 + 1?')
userAnswer = input("Your answer:")
if userAnswer == ans1:
    print('Correct!')
else:
    print('Incorrect.')

Currently, it will just go to the second file and play the second file until the playlist is finished. Please help and thank you in advance!


Solution

  • Your problem is that you have an "infinite" loop in your play():

        while songs:
            if not pygame.mixer.music.get_busy():
                if len(musicList) == 0:
                    print('Playlist has ended.')
                    songs=False
                else:
                    pygame.mixer.music.load(musicList[0])  
                    print('Now playing: '+musicList[0])
                    pygame.mixer.music.play()
                    musicList.pop(0)
    
    

    so the function call never ends before all the songs are over, and therefore you get to these lines:

    ans1 = 2
    print('What is 1 + 1?')
    userAnswer = input("Your answer:")
    if userAnswer == ans1:
        print('Correct!')
    else:
        print('Incorrect.')
    

    When the music is over.

    To solve this problem you need to redesign your program. If you will do the program with full GUI of pygame, you can control both the input and the music at the same time, check every few seconds if there is input or the music, and over and replace it.

    Or if you don't want to do it, you can read the documentation about threading in python: https://docs.python.org/3/library/threading.html

    This will allow you both to run a while loop (to check if the music is over) and wait for the user input at the same time.