2

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • You should use threads – politinsa Aug 23 '20 at 11:08
  • You have to use at least 2 threads or processes to do this. One for play the sound and the other for printing the text. – Kasper Aug 23 '20 at 11:10
  • Does this answer your question? [Whenever I use the "playsound" to play sound in the background the rest of my game does not load](https://stackoverflow.com/questions/54053953/whenever-i-use-the-playsound-to-play-sound-in-the-background-the-rest-of-my-ga) – Tomerikoo Oct 10 '21 at 09:08

1 Answers1

4

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()
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22