Search code examples
pythonpython-playsound

How to play music and print text at the same time?


I want to make this cool program that plays music while listing my life goals. I can't get the music to play while the text prints. How can I do this?

from playsound import playsound
import time

print('My life goals are:')
playsound('spongebob.mp3.mp3', 1)
print('Life goal 1 \n')
time.sleep(0.2)
print('Life goal 2 \n')
time.sleep(0.2)
print('Life goal 3 \n')
time.sleep(0.2)
print('Life goal 4')
time.sleep(0.2)
print('Life goal 5')

Any idea of how I can do this?


Solution

  • You can achieve that by creating two threads:
    First thread would play your favorite music.
    The second will list your life goals.

    from playsound import playsound
    import time
    
    from threading import Thread
    
    def life_goal_printer():
        print('My life goals are:')
        LIFE_GOALS = ['code python' , 'eat', 'sleep' ]
        for life_goal in LIFE_GOALS: 
            print(life_goal)
            time.sleep(0.2)
    
    def favorate_music_player():
        FAVORATE_SONG = 'spongebob.mp3.mp3'
        playsound(FAVORATE_SONG, 1)
    
    t1 = Thread(target=life_goal_printer)
    t1.start()
    
    t2 = Thread(target=favorate_music_player)
    t2.start()