I am making a hangman python game to get to know the python syntax but as the code plays the background music .wav file, the code delays until the end of the music instead of running simultaneously.
I have tried using the os.system command (from the os library) and also subprocess.popen() in order to open the music in a new script window using a different script file but nothing worked.
import os
def music(): #this is the in-game function that is supposed to run the music
os.system("musicforhangmaninit.py")
import winsound #this is the command that plays the .wav file music created earlier by this script
winsound.PlaySound('hangmanadditionals.wav', winsound.SND_FILENAME)
no error messages appeared but I think that I got the os.system() function wrong because it seems to do nothing at all, the subprocess.popen() played the music but still delayed the game. (the goal output was the music playing simultaneously with the game I made)
P.s. : I prefer a solution that works on all the operating systems or at least Linux and windows
Related
I currently have an audio file in the correct directory but I can't seem to find a command that will play and loop the song. Is it the same as just playing the sound? If not, what is the syntax to play the music?
Pygame Zero seems to make this easy. The methods for playing longer music tracks are different than those for playing short sound clips.
If you want to play a music file called tune1 place it inside a directory below your code file called "music" with the file name tune1.mp3 or tune1.ogg.
Inside your program running the following will play the music on an infinite loop
music.play('tune1')
References:
Build-ins - Music
I would like to run my python script while I'm working on other things. For example, I want to run the python script while I'm watching a movie. But I don't want to exit full screen and go to the interactive shell and then go back.
I tried to create a batch file and run from the command line. But it's still not as neat and straight-forward as single-button functionality.
If I want to check the time while I'm watching a movie on hulu website.
python script:
import datetime
datetime.datetime.now()
I wonder if I can set a hotkey so that while I'm on other applications, I can just press the key and then python script will run itself in the background.
Try using keyboard module (allows us to assign custom shortcut keys):
import pyttsx3
import datetime
import keyboard
def time():
engine = pyttsx3.init()
hours = int(datetime.datetime.now().time().hour)%12
if not hours:
hours = 12
engine.say("the time is " + str(hours) + " " + str(datetime.datetime.now().time().minute))
engine.runAndWait()
def keyPress():
keyboard.add_hotkey('+', lambda: time())
keyboard.wait()
keyPress()
WHAT THIS PROGRAM DOES:-
This program a first creates a custom shortcut (assigns it to keyboard key +(change this to whatever hotkey combination you want)). Upon pressing this key, a function called time() gets called, which makes use of windows TTS, to tell your the current time (via voice functionality like siri, alisa etc).
HOW DOES THIS WORK:-
I made use of external libraries keyboard(necessary) and pyttsx3(optional), where the module keyboard allows us to define our custom hotkeys and create a event handler for keyboard events, and pyttsx3 makes use of windows Text to Speech feature to read some text via speech (aka voice). I made use of voice functionality, to not interrupt your flow while your are watching something online.
HOW TO SET IT UP:-
Copy the code, and save it as a .pyw file (notice the w in the
end). The difference between a regular .py an a .pyw file is
that, .py invokes console (~commandline) equivalent tool for
execution and executes in foreground, on the other hand a .pyw
file runs in the background at all times (i.e the console won't show
up). So it won't require you to manually open the console at all
times for executing the script as the script will be running in the
background at all time.
Copy this file (example.pyw) in the startup folder of your OS (any
file in this folder will automatically execute once the operating
system has started). What this will do is when your OS, will boot
your example.pyw file will automatically start executing in the
background, so you won't have to manually launch it at every system
startup. And since it is in the background it won't interfere with
your work. (if you're on windows OS, you can access your startup folder by typing shell:common startup on your run and pressing enter) (adding files to this folder requires root privileges)
HOW TO USE IT:-
While using your system press + (for my case), and your OS will tell you what the current time is. (though it requires your OS to have correct time)
PROS:-
Upon using this for long time I can tell you I never encountered a
single application in which the custom defined hotkey won't work.
Slim to None time required after keypress, for command execution.
A lot resistant to spam of hotkey's. e.x. You may press the
hotkey 100 times but the calls won't be made unless the previous
command has completed execution.
CONS:-
Calling the script for the first time after Bootup, may cause a
little latency in command execution (but only for once, i.e
subsequent calls would be really fast)
P.S:-
It is optional to use pyttsx3, I used it as it makes checking time a lot more easier then reading text or something (at least for me).
Secondly, this process could be made more efficient if you want.
RECOMMENDATIONS:-
Alternatively, If you are familiar with AHK (AutoHotKey) then, doing what i just told on a .ahk script would be a piece of cake, and it's scripts are even faster than my Python one. (Honestly I would definitely Recommend you to use AutoHotKey as it is a really robust language, when it comes to make efficient Operating System scripts)
I'm developing a music player in Python 2.7 and I have a problem I can not solve.
Sometimes it's necessary to unmount the SD card I'm playing from.
Since pygame still keeps the last played file open after pygame.mixer.stop() and pygame.mixer.quit()
commands, it was not possible to unmount the card.
So I modified my code to use the file open and close commands to be able to properly close the played file before the unmount. This way the unmount is working fine.
My issue is with this solution that python always hangs during the playback of the first music. There are no any exceptions or error messages, the playback just stops and the program doesn't respond any user input, even the Ctrl+C doesn't work to quit the execution from shell.
This hanging always happens at a random time, somewhere between 1 and 40 seconds after the playing has started.
If I open the file directly with the pygame.mixer.music.load(myfile) command, not using the open/close solution, I never have any hanging, the program plays properly even for several hours long.
What solution shall I use to be able to properly close the played file (to be able to unmount the memory card) and also avoid hanging of the program?
Here is the relevant part of my code. It closes the previous playing session and starts playing a new file.
FailedMusicLoad = 0
pygame.mixer.music.stop()
pygame.mixer.stop()
pygame.mixer.quit()
try:
PlayedMp3File.close()
except AttributeError:
pass
try: # test if selected music file can be loaded
PlayedMp3File = open(Selectedmp3)
except IOError:
FailedMusicLoad = 1
if FailedMusicLoad <> 1:
pygame.mixer.init(frequency=musicforlength.info.sample_rate)
pygame.mixer.music.set_volume(MainVolume)
pygame.mixer.music.load(PlayedMp3File)
pygame.mixer.music.play()
You could try to load the entire file into memory first by using a memory-mapped file:
import mmap
...
with open(Selectedmp3) as f:
PlayedMp3File = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
pygame.mixer.music.load(PlayedMp3File)
pygame.mixer.music.play()
This way, you only touch the file while loading it into the memory and using with ensures it gets properly closed.
I found a simple workaround to be able to unmount the SD card.
Before unmounting it, I open a dummy mp3 file not from the SD card, but from the local filesystem using the pygame.mixer.music.load() command. I do not start playing this dummy file, just open it.
After that there is no any issue, the SD card seems to be properly released by pygame and I'm able to unmount it.
I have searched for ages for a latency free utility to playing short ".wav" files either through python itself or an os.system() function. If it helps I'm running Ubuntu
Example:
os.system("instantplay /home/fiveSecondClip.wav")
or:
pygame.mixer.play("/home/fiveSecondClip.wav")
Note that pygame won't work because you have to load in the audio first and as far as I know you can't load multiple at once.
The program would need to run in the background so that the python file can be spammed with inputs and still keep up (overlap the audio)
Any ideas as to how I can this?
Try afplay to play it by a terminal. Use one of the two commands below.
import os
import sys
import subprocess
#Plays one music file at a time
subprocess.call(["afplay", "storm-9s.mp3"])
#Can be used to play multiple music files as called
com = ("""osascript -e 'tell application "Terminal" to do script "afplay ./Desktop/storm-9s.mp3; exit"'""")
os.system(com)
I am trying to wait for a song to finish to play the next song.
I am running python 3.4 on windows but am trying to be able to use it on Linux (raspberry pi).
I have used the command subprocess.call([PLAYER, SONG]) to open the mp3 file. It plays in vlc and then stops. I know that I have not incorporated anything for the program to tell python when its finished.
That's where you guys come in. I want to find a command that will wait until the song has finished and when the song is finished, the rest of the code will process.
I would like the command to be able to used on a Linux operating system and I am trying not to have to install any modules.
If modules are definitely needed, I will install them.
You may use VLC python bindings to get the different information about the VLC player.
There are different methods that can provide your different information. You may achieve your solution by using the get_state(self) method, it provides the state information of the player. So, when the song is completed the VLC state would be stopped.
Sample code:
import vlc
def setup_player(filename):
vlc_instance = vlc.Instance()
media = vlc_instance.media_new(filename)
player = vlc_instance.media_player_new()
player.set_media(media)
player.play()# Start the player
print player.get_state()# Print player's state
player.stop()# Stop the player
print player.get_state()# Print player's state
setup_player('filename')#Put media file name/location here
I hope it was helpful.