Search code examples
pythonpygameoperating-systempygletwinsound

How to play an mp3 file while a text based program is loading? Python


So i'm making a text based python file using inputs and if statements. But how do i play an mp3 file while the inputs are loading? I'm using Ubuntu btw

I have already tried pyglet, winsound, os but none of them work I've tried pygame but it doesn't play the file while loading the inputs


print("Welcome user")
name = input("Client name: ")
gender = input("Mr or Miss: ")
age = input("Client age: ")
room = input("Room: ")
sure = input("""All done!!!
Press any key to show the view!""")

welcome = f"""Welcome to room {room} {gender}. {name}!
Have a nice stay"""

if sure == "a":
    print(welcome)
else:
    print(welcome)

Os - "Module os has no startfile member"

pyglet - Doesnt import

winsound - Doesn't play the file

The only sucessfully atempt at playing the mp3 file was when i used pygame, but even then it wouldn't load the inputs at the same time Anyways, here's the code:

import pygame
import time
pygame.init()

pygame.mixer.music.load("elevmusic.mp3")

pygame.mixer.music.play()

time.sleep(10)

print("Welcome user")
name = input("Client name: ")
gender = input("Mr or Miss: ")
age = input("Client age: ")
room = input("Room: ")
sure = input("""All done!!!
Press any key to show the view!""")

welcome = f"""Welcome to room {room} {gender}. {name}!
Have a nice stay"""

if sure == "a":
    print(welcome)
else:
    print(welcome)

Solution

  • Following code works for me:

    But it's almost no change to the code that you posted.

    I'm running on linux with python 3.6 and pygame 1.9.6.

    If it doesn't work, then please specify OS, python version and pygame version.

    import pygame
    import time
    
    pygame.init()
    
    pygame.mixer.music.load("elevmusic.mp3")
    print("loaded")
    
    pygame.mixer.music.play(loops=-1)  # repeat indefinitely
    print("started play")
    
    print("Welcome user")
    name = input("Client name: ")
    gender = input("Mr or Miss: ")
    age = input("Client age: ")
    room = input("Room: ")
    sure = input("""All done!!!
    Press any key to show the view!""")
    
    welcome = f"""Welcome to room {room} {gender}. {name}!
    Have a nice stay"""
    
    pygame.mixer.music.stop()
    # pygame.mixer.music.fadeout(1000)  # or use fadeout 
    if pygame.version.vernum >= (2, 0):
        # free some resources. but this exists only for newer
        # versions of pygame
        pygame.mixer.music.unload()
    
    if sure == "a":
        print(welcome)
    else:
        print(welcome)
    
    print("now simulating some activity without music")
    time.sleep(10)
    print("program ends")