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:\Users\Nutzer\Desktop\gui\victory.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:\Users\Nutzer\Desktop\gui\victory.mp3"
Fehler beim Starten von MCI.
Error 305 for command:
close "C:\Users\Nutzer\Desktop\gui\victory.mp3"
Zusätzliche Zeichen nach einer Zeichenkette mit Anführungszeichen sind nicht erlaubt.
Failed to close the file: "C:\Users\Nutzer\Desktop\gui\victory.mp3"
Traceback (most recent call last):
File "C:\Users\Nutzer\Desktop\gui\wer_support.py", line 3, in <module>
playsound._playsoundWin("C:\\Users\\Nutzer\\Desktop\\gui\\victory.mp3",block=True)
File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python39\lib\site-packages\playsound.py", line 72, in _playsoundWin
winCommand(u'open {}'.format(sound))
File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python39\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 277 for command:
open "C:\Users\Nutzer\Desktop\gui\victory.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:\Users\Nutzer\Desktop\gui\victory.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:\Users\Nutzer\Desktop\gui\wer_support.py", line 1, in <module>
import mp3play
File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python39\lib\site-packages\mp3play\__init__.py", line 4, in <module>
from .windows import AudioClip as _PlatformSpecificAudioClip
File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python39\lib\site-packages\mp3play\windows.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?
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:
"A problem occurred in initializing MCI" playsound issues
a problem occurred in initializing MCI python
why python modules playsound is not working?
Not able to play audio file in python
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.
In Python, I run ffmpeg to convert a video to a .mp4 file. However, for some reason, the video it creates is not compatible with anything (I'm pretty sure it's corrupted). The code looks like this:
import os
os.system("ffmpeg -i Images/i1.mov Images/edited.mp4 -loglevel quiet")
os.remove("Images/i1.mov")
os.rename("Images/edited.mp4", "Images/i1.mp4")
However, the video file created doesn't play.
I am getting an error that just says killed. What am I doing wrong?
Edit: I also tried converting to .WebM rather than .mp4, and it had no effect. (it still gave the same error)
I am using python 3.6.8 with Linux ubuntu and I have a py.file (pyinst_tester.py) that I want to test pyinstaller with:
I have three files (pyinst_tester.py) (bell.mp3) (filetotestadd.txt)
The (pyinst_tester.py), plays a bell sound, only after reading a play command from the text file (filetotestadd.txt)
If I use pyinstaller, i can get this to work, however, when (pyins_teseter.py) turns to an EXE....it does not contain (bell.mp3) or (filetotestadd.txt), as removal of either of them from the directory, gives no sound.
as instructed in the pyinstaller manual and it is added to the spec file indeed as expected, but I would have thought that when you make a single file EXE, it contains, (filetotestadd.txt) and (bell.mp3) INSIDE IT thus making these files redundant from the directory they are in and irrelevant to the EXE...thus removable.
AM I missing something ??...and if not, how can i get one EXE file, that has both, the mp3 and the text file INSIDE IT ?
Thank you
What am I not understanding properly.
I tried:
pyinstaller -F --add-data 'filetotestadd.txt:.' pyinst_tester.py
this is the code I am trying to turn to exe.
import subprocess
f=open('testfile1','w')
f.write('This has worked')
f.close()
f=open('testfile1','r')
test=f.readline()
f.close()
print(test)
f=open('filetotestadd.txt','r')
read=f.readline()
if 'play' in read:
subprocess.call(['cvlc','bell.mp3'])
I am closing this question. I have tried everything and i cannot do it. and i am getting no more feedback. therefore i am going to close it.
pyinstaller -F --add-data doesnt do it.
I just started using pydub. I am confused that should we download the music to find the path or we need to do something else? Because the example below seems like it already have the file in his terminal or IDE. But I don't see how can I import a music into the IDE.
from pydub import AudioSegment
song = AudioSegment.from_wav("never_gonna_give_you_up.wav")
You need to have the never_gonna_give_you_up.wav audio in the same directory as the Python script for this to work. Or if you want to use it from another directory, you need to provide the full path, for example:
song = AudioSegment.from_wav("D:\Music\never_gonna_give_you_up.wav")
I am attempting to call ffmpeg to create an image from a frame in a video, I am using python to do this with subprocess.Popen on a mac, eventually this will move to a unix server.
I can successfully create a video from the command line with this line
ffmpeg -i /Users/bimemployee/Movies/ski\ commute.m4v -r .5 -vframes 1 -ss 00:01:14 /Users/bimemployee/Movies/untitled\ folder/image-%d.jpeg
I then turn this into a python iterable and passed it Popen
s=["ffmpeg","-i","Users/bimemployee/Movies/ski\ commute.m4v","-r","1","-vframes","1","-ss","00:01:14","/Users/bimemployee/Movies/untitled\ folder/image-%d.jpeg"]
subprocess.Popen(s)
When I do so I get the standard info screen from ffmpeg and an error that says Users/bimemployee/Movies/ski\ commute.m4v: No such file or directory
Why would this path work ok from the command line but not from python?
Secondly is their a better library for handling this, the ones I could find don't seem to be active projects or don't work with straight python but require things like cython.
Thanks,
CG
You're missing the opening forward slash:
/Users/bimemployee/Movies/ski_commute.m4v
is not the same as
Users/bimemployee/Movies/ski_commute.m4v