如何在不中断或暂停 python 中的其他代码的情况下随机播放音乐文件夹?
How can I shuffle a folder of music without interupting or pausing other code in python?
简而言之,我想在后台随机播放一个包含 .mp3 文件的文件夹,这样我仍然可以使用程序 运行。我在 Mac OS X 上。我已经设法使用 Glob
获取列表中的所有文件,然后我可以使用 playsound 插件播放它们 found here. 但是这个脚本阻止从 运行 到所有歌曲都完成的任何其他内容都不是我想要的。我尝试使用此代码 pygame
...pip install pygame
(成功运行),然后...
import pygame
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
然而,这总是 returns 相同的错误,pygame.error: MPEG file does not have any audio stream.
所以我在列表中有这些文件,但无法在后台播放它们。有人可以帮忙吗?
代码更新:
我实际上设法让它用下面的代码播放声音...
import time
import glob
import pygame
pygame.mixer.init()
def play_my_mix(data = "error"):
for file in glob.glob("data/music/mix/*.mp3"):
pygame.mixer.music.load(file)
pygame.mixer.music.play()
print("test")
play_my_mix()
print("apple")
time.sleep(15)
但是音频质量很差。听起来有点扭曲和缓慢。 time.sleep(15)
行是用来保持程序 运行 的,否则它就会停止,考虑到这是一个测试,这没关系。但是我确实将其更改为...
x = 1
while x == 1:
print("good")
万一跟时间有关系但根本没变
所以我用编辑中提到的更新代码修复了第一部分。我通过将 pygame.mixer.init()
更改为 pygame.mixer.init(44100, -16, 2, 2048)
解决了音频延迟的第二个问题
简而言之,我想在后台随机播放一个包含 .mp3 文件的文件夹,这样我仍然可以使用程序 运行。我在 Mac OS X 上。我已经设法使用 Glob
获取列表中的所有文件,然后我可以使用 playsound 插件播放它们 found here. 但是这个脚本阻止从 运行 到所有歌曲都完成的任何其他内容都不是我想要的。我尝试使用此代码 pygame
...pip install pygame
(成功运行),然后...
import pygame
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
然而,这总是 returns 相同的错误,pygame.error: MPEG file does not have any audio stream.
所以我在列表中有这些文件,但无法在后台播放它们。有人可以帮忙吗?
代码更新:
我实际上设法让它用下面的代码播放声音...
import time
import glob
import pygame
pygame.mixer.init()
def play_my_mix(data = "error"):
for file in glob.glob("data/music/mix/*.mp3"):
pygame.mixer.music.load(file)
pygame.mixer.music.play()
print("test")
play_my_mix()
print("apple")
time.sleep(15)
但是音频质量很差。听起来有点扭曲和缓慢。 time.sleep(15)
行是用来保持程序 运行 的,否则它就会停止,考虑到这是一个测试,这没关系。但是我确实将其更改为...
x = 1
while x == 1:
print("good")
万一跟时间有关系但根本没变
所以我用编辑中提到的更新代码修复了第一部分。我通过将 pygame.mixer.init()
更改为 pygame.mixer.init(44100, -16, 2, 2048)