1
votes

I am trying to make a simple program that plays some narration, and has a sound effect on a trigger. Being new to python, I am just building up functions in layers. Getting music to work was easy, as it should be, but I cannot get sound to work.

I have read of a few people with similar issues, but either they are also unsolved, or the symptoms are slightly different, and the solutions don't work for me.

I have tried this on a pi3 (which is the end target), and windows 7, both running latest python 3, and pygame.

import pygame
import time
import os

pygame.mixer.init()
#pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
pygame.mixer.music.load("English.mp3")
pygame.mixer.music.play()
print (os.getcwd()) 
shot = pygame.mixer.Sound("gun-gunshot-02.wav")
shot.play()

while True:
    Time.sleep(1) # for testing and irritation prevention if sound ever plays
    shot.play()

I should also note that the sound effect does work if I play it using music, but of course it replaces the narration.

Error is as follows same on both machines, same with both mp3 and wav:

C:\Users\me\Documents\Interrupter Traceback (most recent call last): File "C:/Users/me/Documents/Interrupter/simpletest.py", line 11, in shot = pygame.mixer.Sound("gun-gunshot-02.wav") pygame.error: Unable to open file 'gun-gunshot-02.wav'

Thanks in advance

2
@SherylHohman have you tried to see if the user running the script has permission to access this file? - Rodrigo Alencar
@RodrigoAlencar jjmc is the OP, I just edited the post. - SherylHohman
@jjmc Also, try this shot = pygame.mixer.Sound(file="gun-gunshot-02.wav") - Rodrigo Alencar
In cases like these, the most common cause is that the file is not in the folder where you – the programmer – believe it is. - Jongware
@RodrigoAlencar I have tried that to no avail, also the file and folder are correct I used os.getcwd() to confirm this on both windows raspbian - jjmc

2 Answers

1
votes

So I have solved the issue, which is of file compatibility.

I don't know what the right kind of wav file is (other than uncompressed). I had tried using a wav but it did not work.

However I finally tried .ogg since that was the only thing listed as working in the online manual for pygame. As soon as I used .ogg everything worked as planned.

For anyone else with this issue I used Audacity to export my .mp3 and .wav files to .ogg using defaults.

0
votes

Pygame is supporting only 2 type of files. OGG and WAV

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

for more information please visit to

https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound