简体   繁体   English

我想同时播放音乐和打印文本 (Python)

[英]I want to play music and print text at the same time (Python)

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?知道我如何做到这一点吗?

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM