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.
Related
I am trying to use python to convert files from mp4 to mp3. After some research most places recommend moviepy. I used the command pip install moviepy and it seemed to go off without a hitch. I go to VS Code and enter what a youtube video told me to enter (I know its not recommended to do that, I just wanted to see if it would work). This is what I have
`
#This code should convert a .mp4 file into a .mp3 file
#This imports the moviepy package
from moviepy.editor import *
#here are the names of my files (I have subbed out actual files names)
mp4_file = "file_name.mp4"
mp3_file = "file_name.mp3
#Here is the the audio being stripped from the .mp4 file
video_clip = VideoFileClip(mp4_file)
audio_clip = video_clip.audio
#this is writing the audio to a .mp3 file at the path that is specified.
audio_clip.write_audiofile(mp3_file)
#this closes the conversion code
audio_clip.close()
VideoClip.close()
`
After running the code I get this error:
RuntimeError: No ffmpeg exe could be found. Install ffmpeg on your system, or set the IMAGEIO_FFMPEG_EXE environment variable.
There is a bunch of gibberish above it but that is the final line that gets spit out.
After looking up what the issue is I tried to input:
`
from moviepy.config import change_settings
change_settings({"FFMPEG_BINARY": "/usr/bin/ffmpeg"})
`
And it also did not work. I have tried searching for where ffmpeg is and it is not in /usr/bin/ffmepg or /usr/local/bin/ffmpeg like most sources I have looked at tell me it should be.
I have tried installing ffmpeg on its own by doing pip install ffmpeg and 'brew install ffmpeg'. Both of those go off without a hitch as well but the error still pops.
I am using a macbook air m1 and I have I think everything I need installed already so I am so lost on what is causing this error to pop.
Can someone please help?
I have tried installing ffmpeg on its own as well as searching for the file directly.
I should expect to get the .py file to run fine.
I instead get the error seen above:
RuntimeError: No ffmpeg exe could be found. Install ffmpeg on your system, or set the IMAGEIO_FFMPEG_EXE environment variable.
try to use this code which is i got
import moviepy.editor
import os
os.environ["IMAGEIO_FFMPEG_EXE"] = "/usr/bin/ffmpeg"
mp4_file = "file_name.mp4"
mp3_file = "file_name.mp3"
# Replace the parameter with the location of the video
video = moviepy.editor.VideoFileClip("mp4_file")
audio = video.audio
# Replace the parameter with the location along with filename
audio.write_audiofile("mp3_file")
if it is still not find the ffmpeg then find its actual path and note that
I was making a program using pywhatkit to send WhatsApp messages. However, when trying to import pywhatkit, the following exception is raised:
(Sorry, I was not able to copy the error message.)
Can anyone tell me why this is happening?
One of the dependencies of pywhatkit is the pyautogui module (see here for what pyautogui is). REPL.it runs on Linux, a Unix-like OS; on Unix, pyautogui requires Xlib (hence, Xlib.error.XauthError). On importing pywhatkit, Xlib attempted to open the .Xauthority file, but failed to do so, in this case because the file does not exist. I believe this behavior has to do with REPL.it itself, i.e., there's nothing you can do about it.
For background on what the .Xauthority file is, refer to this AskUbuntu question.
I am curious to know if I send someone a python file with embedded sound files, if it will still play on another computer or if the file has to be in their drive.
Here I am using playsound, but I can use other modules as needed.
from playsound import playsound
playsound('partyhorn.wav')
The answer is no. The file has to be in the same relative directory.
Okay I am newer to python and have been researching this problem but I can't find anything like it so I am not sure what is going on.
I am creating a program that involves sage and it has a message cue. We have this set up on a development machine, so I know it works but I was wanting to set it up on my own computer so I could get a better understanding of how it all works and make it easier to develop for myself.
To start up sage, we run a script that calls sages main binary file and passes it an executable .py file. (./sage/sage ./sage_server.py) This creates an error in the sage_server.py file:
Traceback (most recent call last):
File "./sage_server.py", line 23, in <module>
from carrot.messaging import Publisher
ImportError: No module named carrot.messaging
But whenever I run that file just in the terminal (./sage_server) the import works fine and isn't until line 27 that there is an error when it tries to import something from sage.
Does anyone know what would cause the error when it is being called by something else? I am very lost as to what would be causing this.
Sage has its own python, separate from the system libraries. This "carrot" module, whatever it is, must be installed in whatever python ./sage_server.py uses, but not in Sage.
You should be able to use either
[your-sage] -sh
to start up a Sage shell and use easy_install, or you could get whatever carroty package you're using, find its setup.py file, and then run
[your-sage] -python setup.py install
where obviously your-sage is the path to your sage.
Things get a little trickier if the install process isn't setup.py-based.
I've recently come back to a project having had to stop for about 6 months, and after reinstalling my operating system and coming back to it I'm having all kinds of crazy things happen. I made sure to install the same version(2.6) of python that I was using before.
It started by giving me strange tkinter error that I hadn't had trouble with before, the program is relatively simple and the 2 or 3 bugs that were left when i quit, I had documented and weren't related to the interface.
Things got even weirder when the same error would pop up even after I had removed the offending section of code. In fact, the traceback pointed to a line that didn't even exist in the module it was referencing, eg: line 262 when the module was only 200 lines long.
After just starting a completely new file for the main module and copy/pasting it finally recognized that the offending code was gone and I stopped getting the error only to find that any updates to the code I made in another module didn't show up when I restarted the program through the shell. (I didn't forget to save.) After fiddling with this, of course, the old interface error came back, only in a different section of code that had been working previously.
In fact, if I revert back to the files I had six months ago, the program works fine. As soon as I change anything in the main module, however, the interface bug comes back.
Here's the original error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\PyStuff\interface.py", line 202, in dispOne
__main__.top.destroy()
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1938, in destroy
self.tk.call('destroy', self._w)
TclError: can't invoke "destroy" command: application has been destroyed
I'm guessing something else is going on here other than my own poor programming. Anyone have any ideas?
Edit: Thinking back, I believe I read something about it being a bad idea to run Tkinter programs through IDLE's shell, and it appears, at least, that the TclError has vanished if I instead start the main module by double clicking the .pyc file. Perhaps my problems were just a combination of that plus the timestamp/PYTHONPATH issues mentioned below by Chris Atlee and Vlad?
I've had something similar happen. The cause for my problems was that my source control software (hg) was setting the date of files to a date in the past. Because of this, python chose to use previously generated .pyc files which had newer timestamps.
The solution was to delete all the .pyc files before testing the code.
Check your PYTHON_PATH variable, you probably have an older version of the file.
Also start your python interpreter and type the following commands to check the path:
import sys
print sys.path
Take a careful look at the output and make sure you don't have any old directories sitting there.