Skip to content
Advertisement

Different sound playing modules not working

I created a program for my little sister to learn math and now want to add sound. So looked up on how to add sound to my program and found the winsound module. I wrote this code:

import winsound

winsound.PlaySound("victory.wav", winsound.SND_FILENAME)
stopper = input("Input something to stop the program!")

But for some reason it only plays the default windows sound. (Bliiiiiingg)

The file victory.wav is located in the same folder as the python script. Then I saw someone else having the same problem as me and he said that adding the full path solved the problem. So I did that:

winsound.PlaySound(r"C:UsersNutzerDesktopguivictory.wav", winsound.SND_FILENAME)

But it still didn’t work. So I tried different methods of adding the path:

winsound.PlaySound("C:/Users/Nutzer/Desktop/gui/victory.wav", winsound.SND_FILENAME)
# and
winsound.PlaySound("C:\Users\Nutzer\Desktop\gui\victory.wav", winsound.SND_FILENAME)

Still not working. Then I decided to switch modules, so I installed the playsound module and wrote the following code:

import playsound
playsound.playsound("victory.wav",block=True)

It said that it could not play the file, which means that it found the file. We’re making progress. So I changed the file extention to .mp3 and added the full path again:

playsound._playsoundWin("C:\Users\Nutzer\Desktop\gui\victory.mp3",block=True)

Now it said something different:

Error 277 for command:
        open "C:UsersNutzerDesktopguivictory.mp3"
    Fehler beim Starten von MCI.

    Error 305 for command:
        close "C:UsersNutzerDesktopguivictory.mp3"
    Zusätzliche Zeichen nach einer Zeichenkette mit Anführungszeichen sind nicht erlaubt.
Failed to close the file: "C:UsersNutzerDesktopguivictory.mp3"
Traceback (most recent call last):
  File "C:UsersNutzerDesktopguiwer_support.py", line 3, in <module>
    playsound._playsoundWin("C:\Users\Nutzer\Desktop\gui\victory.mp3",block=True)
  File "C:UsersNutzerAppDataLocalProgramsPythonPython39libsite-packagesplaysound.py", line 72, in _playsoundWin
    winCommand(u'open {}'.format(sound))
  File "C:UsersNutzerAppDataLocalProgramsPythonPython39libsite-packagesplaysound.py", line 64, in winCommand
    raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
    Error 277 for command:
        open "C:UsersNutzerDesktopguivictory.mp3"
    Fehler beim Starten von MCI.

Translated it means “Error starting MCI”.

Then I decided to install pygame and use the mixer libary:

import pygame.mixer as mixyy

mixyy.init()
mixyy.music.load("victory.mp3")
mixyy.music.play(loops=0)

input = input("Press enter to stop the program.")

Surprisingly, that actually worked. But it caused the compiled file size to go from 16MB to 70MB and the compiled file could not even open.

So I scrapped that idea and found a module called mp3play, and copied the example code, and adjusted it for me:

import mp3play

filename = r'C:UsersNutzerDesktopguivictory.mp3'
clip = mp3play.load(filename)

clip.play()

import time
time.sleep(min(30, clip.seconds()))
clip.stop()

Now it said this:

Traceback (most recent call last):
  File "C:UsersNutzerDesktopguiwer_support.py", line 1, in <module>
    import mp3play
  File "C:UsersNutzerAppDataLocalProgramsPythonPython39libsite-packagesmp3play__init__.py", line 4, in <module>
    from .windows import AudioClip as _PlatformSpecificAudioClip
  File "C:UsersNutzerAppDataLocalProgramsPythonPython39libsite-packagesmp3playwindows.py", line 27
    print 'Error %s for "%s": %s' % (str(err), txt, buf)
          ^
SyntaxError: invalid syntax

I don’t see anything wrong with the syntax, as I literally copied the example from their documentation.

I just can’t seem to get anything to work. Things I also tried:

  • Using a different file.
  • Using various filetypes.
  • Reinstalling windows.
  • Trying on linux.
  • Restarting my computer.
  • Trying on a different computer.
  • Trying on mac.
  • Using a different python interpreter.
  • Using a different code visualizer (VSC, Pycharm, Idle).

Could somebody please tell me how to fix this?

Advertisement

Answer

You actually asked a lot of questions at the same time, and it might have been better to focus on one each time. However, since a number of questions are related, I’ll try to answer them here:

winsound

At my system, winsound seems to be working fine. The following code works for me:

import winsound

winsound.PlaySound('victory.wav', winsound.SND_FILENAME)

However, the audio file must be a valid WAVE file (not an MP3 file or another audio format) that is supported by the winsound module. If it’s not supported, it will play the system default sound (which you describe as Bliiiiiingg). This can be avoided by passing the winsound.SND_NODEFAULT flag:

import winsound

winsound.PlaySound('victory.wav', winsound.SND_FILENAME | winsound.SND_NODEFAULT)

In this case, when trying to play an invalid file format, you will get the error RuntimeError: Failed to play sound.

Unfortunately, the error message does not specify the cause of the problem. You will get the same error when passing an invalid path as when passing a valid path to an unsupported file. However, generally Windows applications do support forward slashes ('/') as well as backslashes ('\'). In case of doubt, temporarily copy the file to the same directory as your script and remove the directory part of the path at all, so you can identify the problem.

Note that the WAV format is a container format, which supports different encodings. It is possible that not all formats/encodings are supported, so you just have to try which one works or not.

playsound

I also tried playsound, which did work for some of my WAV and MP3 files, but not for all of them. If it didn’t work, I got one or more of the following errors:

playsound.PlaysoundException:
    Error 259 for command:
        play sample.mp3 wait
    The driver cannot recognize the specified command parameter.
playsound.PlaysoundException:
    Error 263 for command:
        open sample.mp3
    The specified device is not open or is not recognized by MCI.
playsound.PlaysoundException:
    Error 277 for command:
        open "sample.mp3" alias playsound_0.9221509684918991
    A problem occurred in initializing MCI.

There are several bug reports at GitHub (see issues #36, #83, #113, #120 and #121). There have also been questions about this on Stack Overflow already:

To me it seem that playsound has some problems with certain file formats. Possible solutions / work-arounds include:

  • Downgrade to playsound 1.2.2 (python -m pip install playsound==1.2.2) — This was mentioned somewhere and I noticed that some files can indeed by played using 1.2.2 that cannot be played using 1.3.0, but it still doesn’t play all my files.
  • Recode the MP3 file using e.g. Audacity — This didn’t work for my files.
  • Save the file in another format (e.g. convert MP3 to WAV) — This didn’t work for my files.

Note that arbitrarily changing file extensions is never a good idea. Please make sure what the type of the file is, and make sure it has the correct extension. Renaming an WAV file to ‘.mp3’ or vice versa does not magically make it playable.

pygame

The same pygame code worked for me as well. I’m not sure why 70 MB is a problem, or what framework you use to compile the code (I assume py2exe or something similar). If this really is a problem, you might ask another question about this. There might be a way to decrease the size.

mp3play

The mp3play module seems to be heavily outdated and not maintained anymore. Its website is dead, and the last release on pypi was in 2008. The code is written in Python 2.x, and that’s the reason you get the syntax error. (The syntax error is not in your code, but in the library.)

TL;DR

  • winsound works fine with supported filetypes (WAV only).
  • playsound seems to work fine with some WAV or MP3 files only.
  • pygame works fine as well. Not sure why size is an issue, but there might be solution for that.
  • mp3play is outdated, don’t use it.
  • don’t arbitrarily change file extensions.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement