pythonraspberry-pipygamemixer

pygame.mixer.music plays audio fine but pygame.mixer.Sound gives error 'Unable to open file'


I have a simple code in which i want to play an audio file using pygame's mixer class. When I do:

import pygame

dir_path = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(dir_path, "mp3s", 'info.mp3')

pygame.mixer.init()
pygame.mixer.music.load(path)
pygame.mixer.music.play()

it works just fine. But when I try the same with:

import pygame

dir_path = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(dir_path, "mp3s", 'info.mp3')

pygame.mixer.init()
mysound = pygame.mixer.Sound(file=path)
pygame.mixer.Sound.play(mysound)

It gives error Unable to open file '/home/pi/myproject/mp3s/info.mp3'

I've tried googling and only thing I could find was either to try pygame.init() or pygame.display.set_mode((400, 300)) neither of which worked for me... Any ideas on what might be wrong? I'm using Raspberry Pi with Raspbian installed and python 3.7 with pygame 1.9.6


Solution

  • You can't use the Sound class for mp3 playback, as it only supports ogg and wav.

    See the docs of pygame.mixer.Sound:

    The Sound can be loaded from an OGG audio file or from an uncompressed WAV.

    The only way to play a mp3 file with pygame is to use pygame.mixer.music.