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.
I am making a program in Python which I'll send to other people in our company. The aim of the program is to show which programs are downloaded and not from a list. The problem is that the program is not installed in the same place on every device.
How can I check if a program is downloaded or not?
only found this:
import os
os.path.exists(c:\.......)
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 Writing The Code That You Can See Under That Article On IDLE It Correctly Works But When I Save The Code As A .py File It Doesn't Opens How I Can Open A .py File Correctly?
import random
from random import randint
random.randint(111111111, 999999999)
(Problem Solved I Erase The The Code That You Can See Under That Article And It Works)
from random import randint
If you are attempting to open a .py file by double clicking on it, you need to have the version of python you want to run it with added to your PATH. Also you need the .py file extension associated with the Python application.
The other way to do this is to have all .py files opened with Idle, Pycharm, Sublime Text, etc (Whatever IDE you sue to write it). This wont automatically run the file however, it will open it in an editable state in your IDE.
Lastly, as it relates to the code you provided, importing randint() is not necessary as you've already imported the entire random module.
I am hoping that someone can help with a Python bindings output question (using vlc.py)
I have a basic test script that uses vlc.py which runs but does not play the video.
import vlc
def setup_player(filename):
vlc_instance = vlc.Instance('--no-audio', '--fullscreen')
player = vlc_instance.media_player_new()
media = vlc_instance.media_new(filename)
player.set_media(media)
print media.get_mrl() # File location to get title
print player.get_length() #Time duration of file -1 means there is no media
print player.get_state() #Player's state
player.play()
setup_player('foo.mp4')
This outputs
file:///Users/admin/Sites/pythontest/foo.mp4
-1
State.NothingSpecial
I am unsure where to install the vlc.py module and hoping someone can help. I'm on MacOs, VLC 2.0.9, Python 2.7.3. Running python through the terminal.
At the moment I have the vlc.py module in the same directory as my test script - and outside of the VLC.app directories and although the script is executing without errors it isn't playing the video or returning any parameters about the specified mp4 file.
Apologies for a banal question! Any help very gratefully received.
It seems that the player.play() function is not blocking, but instead returns immediately.
If the Python script then terminates, the player is destroyed right after it has been created.
If you look at the example player in vlc.py, it has a while True loop at the very end that basically reads key presses over and over again in order to implement a simple user interface.
So if you simply add
while True:
pass
at the end of your function, it should continue playing (terminate with CTRL+C until you implement some sort of user input handling).
As for "installing" the script: Unfortunately, the vlc.py module they provide is just that, a simple stand-alone Python module. It's not packaged as a setuptools distribution that you could just install with pip or easy_install like most other Python modules. That means you can (or rather have to) drop it into a location that will be in sys.path yourself.
The current working directory where you launch your script from works for that, but if you want a more permanent location you could drop it into your Python's site-packages (/Users/<your-username>/Library/Python/2.7/lib/python/site-packages for example if you're using the standard OS X framework Python).
Since the API calls succeed, it means that the bindings work correctly. The problem here is rather that the macos x video output module is not able to instanciate its own window. It must be embedded in a native Cocoa widget.
You can use the qt example from the vlc repository or use the x11 video output module, combined with the MacOS X X11 server (which has to be installed for recent versions of MacOS X).