无法在pygame.mixer中打开任何声音文件

时间:2019-01-13 02:41:01

标签: python pygame

我一直在使用pygame.mixer进行与声音有关的Pygame项目,但遇到了一个似乎无法解决的问题。我无法打开我尝试过的任何声音文件(.mp3和.midi)。

我在PyCharm 2018.3。上使用Python 3。我的Pygame主要是最新的(1.9.3版)。我尝试使用完整路径,已经完成pygame.init()mixer.init(),但是我完全陷入困境。

这是我的代码:

import pygame
from pygame import mixer

pygame.init()
mixer.init(44100, 16, 2, 4096)

f = mixer.Sound("output.midi")
f.play()

print(bool(mixer.get_busy()))
while mixer.get_busy():
    pass

这是错误(文件中的...覆盖了实际的追溯):

Traceback (most recent call last):
  File "/home/.../note.py", line 27, in <module>
    f = mixer.Sound("output.midi")
pygame.error: Unable to open file 'output.midi'

该程序应该打开一个在程序另一部分(我已经注释掉)中创建的.midi文件,并播放直到完成。相反,我只是得到了错误,没有声音播放。

2 个答案:

答案 0 :(得分:0)

MIDI文件不是“声音文件”;它基本上是数字乐谱。您需要MIDI合成器才能从中产生声音。

然后用算法压缩MP3;这不是声音样本序列。

来自the PyGame.Mixer documentation

  

可以从OGG音频文件或未压缩的WAV加载声音。

简而言之,您使用的工具错误。

答案 1 :(得分:0)

当然,您可以使用pygame播放MIDI文件。 MIdI文件的扩展名是.mid(而不是代码中的.midi)。这对我有用:

import pygame

def play_MIDI_pygame(midi_file):
    freq = 44100                               # audio CD quality
    bitsize = -16                              # unsigned 16 bit
    channels = 2                               # 1 is mono, 2 is stereo
    buffer = 1024                              # number of samples
    clock = pygame.time.Clock()
    pygame.mixer.init(freq, bitsize, channels, buffer)
    pygame.mixer.music.set_volume(0.8)         # volume 0 to 1.0

    pygame.mixer.music.load(midi_file)         # read the midi file
    pygame.mixer.music.play()                  # play the music
    while pygame.mixer.music.get_busy():       # check if playback has finished
        clock.tick(30)

midi_file = 'myMidi.mid'
play_MIDI_pygame(midi_file)
相关问题