Yes
Yes

Reputation: 423

pygame mixer pygame error: Unable to open file 'file_location.mp3'

I would like to play my mp3 file in a python script using the pygame.mixer module. I have a script that looks as following:

import pygame
from time import sleep
import os

# print(pygame.version.ver)

pygame.init()
pygame.mixer.init()

my_sound = pygame.mixer.Sound(os.path.join(os.path.dirname(os.path.abspath(__file__)),"sounds","my_sound.mp3"))
while True:
    my_sound.play()
    sleep(0.5)

running this on my windows10 Computer using powershell and python 3.10 results in the error

pygame.error: Unable to open file 'C:\\path\\to\\my\\file\\sounds\\my_sound.mp3'

I have tried installing all the newest >2.0.0 versions, but the error persists. Is there any kind of software drive that I need to have installed in order for this to work? On my old computer I had no problem using pygame.mixer like this without requiring some sort of additional initialization in my script.

Upvotes: 0

Views: 739

Answers (2)

Confused
Confused

Reputation: 82

Convert the .mp3 file into a .wav file, using any sort of online tool, and then it would work. PyGame is very picky about the file type in audio.

Upvotes: 1

AzlanCoding
AzlanCoding

Reputation: 193

I too had this problem, and made a function to help it. This may seem unprofessional but it will work.

def backslashChange(text):
    ans = ''
    temp = text.split("\\\\")
    for items in temp:
        if items == 'C:':
            ans += 'C:\\\\'
        else:
            ans += items 
            ans +='\\'
    ans = ans [:-1]
    return ans

It's a kludge I use till I find a more professional solution. So change your code to this

def backslashChange(text):
    ans = ''
    temp = text.split("\\\\")
    for items in temp:
        if items == 'C:':
            ans += 'C:\\\\'
        else:
            ans += items 
            ans +='\\'
    ans = ans [:-1]
    return ans
import pygame
from time import sleep
import os

# print(pygame.version.ver)

pygame.init()
pygame.mixer.init()

my_sound = pygame.mixer.Sound(backslashChange(os.path.join(os.path.dirname(os.path.abspath(__file__)),"sounds","my_sound.mp3")))
while True:
    my_sound.play()
    sleep(0.5)

Upvotes: 0

Related Questions