问题描述
当我尝试在 pygame 中转发带有 .wav 扩展名的歌曲时,出现错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\default\AppData\Local\Programs\Python\python39\lib\tkinter\__init__.py",line 1884,in __call__
return self.func(*args)
File "C:\Users\default\PycharmProjects\pythonProject1\main.py",line 14,in forward
pygame.mixer.music.play(start = forwarded_pos)
pygame.error: Position not implemented for music type
代码如下:
from tkinter import *
import pygame
root = Tk()
pygame.init()
def play():
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
def forward():
forwarded_pos = pygame.mixer.music.get_pos() + 10
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play(start = forwarded_pos)
play_button = Button(root,text = "Play song",command = play)
play_button.grid(row = 0,column = 0)
forward_button = Button(root,text = "Forward song",command = forward)
forward_button.grid(row = 1,column = 0,pady = 10)
mainloop()
由于我不断收到那个错误,我尝试了这个:
def forward():
forwarded_pos = pygame.mixer.music.get_pos() + 10
pygame.mixer.music.set_pos(forwarded_pos)
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\default\AppData\Local\Programs\Python\python39\lib\tkinter\__init__.py",line 13,in forward
pygame.mixer.music.set_pos(forwarded_pos)
pygame.error: set_pos unsupported for this codec
有什么办法可以解决这个问题吗?
我认为 .wav
格式不支持转发,因此使用任何其他格式(除外 .mp3
)解决此问题也可以。
解决方法
Get_pos 和 set_pos 为我触发了相同的错误。您实际上不需要它们,因为您可以在开始播放音乐时分配 forwarded_pos,如下所示。这似乎不适用于 .wav,但适用于 .ogg 和 .mp3 格式。 (希望这能帮助您解决问题!)
import pygame
from os import path
pygame.init()
pygame.mixer.init()
snd_dir = path.join(path.dirname(__file__),"snd")
song = path.join(snd_dir,'song_name.ogg')
forwarded_pos = 22
mixer = pygame.mixer.music
mixer.load(song)
mixer.play(-1,forwarded_pos)
# doesn't work for wav sounds types
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)