Stop a thread by a tkinter trigger? - multithreading

I'm making a program that displays a messagebox and plays a .wav file through a thread at the same time. The problem is, the sound file is big, and I would like it to stop playing after I press 'OK'. Any help would be appreciated. I'm using Python 3.3 on Windows 7. Here's my code for the box and audio:
t1 = threading.Thread(target=winsound.PlaySound, args=("C:/Interactive Program/LIP Source Files/skyisup.wav", 2))
t1.start()
lipgui.msgbox("The sky is up!")

I fixed it. What I needed to do was pass winsound.SND_ASYNC to winsound.PlaySound() instead of '2'. Then stop the audio by passing winsound.PlaySound(None, 0)!

Related

Pygame Mixer gives Couldn't open audio device on Azure ML [duplicate]

I'm trying to play sound files (.wav) with pygame but when I start it I never hear anything.
This is the code:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
I also tried using channels but the result is the same
For me (on Windows 7, Python 2.7, PyGame 1.9) I actually have to remove the pygame.init() call to make it work or if the pygame.init() stays to create at least a screen in pygame.
My example:
import time, sys
from pygame import mixer
# pygame.init()
mixer.init()
sound = mixer.Sound(sys.argv[1])
sound.play()
time.sleep(5)
sounda.play() returns an object which is necessary for playing the sound. With it you can also find out if the sound is still playing:
channela = sounda.play()
while channela.get_busy():
pygame.time.delay(100)
I had no sound from playing mixer.Sound, but it started to work after i created the window, this is a minimal example, just change your filename, run and press UP key to play:
WAVFILE = 'tom14.wav'
import pygame
from pygame import *
import sys
mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
pygame.init()
print pygame.mixer.get_init()
screen=pygame.display.set_mode((400,400),0,32)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key==K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key==K_UP:
s = pygame.mixer.Sound(WAVFILE)
ch = s.play()
while ch.get_busy():
pygame.time.delay(100)
pygame.display.update()
What you need to do is something like this:
import pygame
import time
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
time.sleep (20)
The reason I told the program to sleep is because I wanted a way to keep it running without typing lots of code. I had the same problem and the sound didn't play because the program closed immediately after trying to play the music.
In case you want the program to actually do something just type all the necessary code but make sure it will last long enough for the sound to fully play.
import pygame, time
pygame.mixer.init()
pygame.init()
sounda= pygame.mixer.Sound("beep.wav")
sounda.play()
pygame.init() goes after mixer.init(). It worked for me.
I had the same problem under windows 7. In my case I wasn't running the code as Administrator. Don't ask me why, but opening a command line as administrator fixed it for me.
I think what you need is pygame.mixer.music:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
You missed to wait for the sound to finish. Your application will start playing the sound but will exit immediately.
If you want to play a single wav file, you have to initialize the module and create a pygame.mixer.Sound() object from the file. Invoke play() to start playing the file. Finally, you have to wait for the file to play.
Use get_length() to get the length of the sound in seconds and wait for the sound to finish:
(The argument to pygame.time.wait() is in milliseconds)
import pygame
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
pygame.time.wait(int(sounda.get_length() * 1000))
Alternatively you can use pygame.mixer.get_busy to test if a sound is being mixed. Query the status of the mixer continuously in a loop.
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick. In addition, you need to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
import pygame
pygame.init()
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
while pygame.mixer.get_busy():
pygame.time.delay(10)
pygame.event.poll()
Your code plays desert_rustle.wav quite fine on my machine (Mac OSX 10.5, Python 2.6.4, pygame 1.9.1). What OS and Python and pygame releases are you using? Can you hear the .wav OK by other means (e.g. open on a Mac's terminal or start on a Windows console followed by the filename/path to the .wav file) to guarante the file is not damaged? It's hard to debug your specific problem (which is not with the code you give) without being able to reproduce it and without having all of these crucial details.
Just try to re-save your wav file to make sure its frequency info. Or you can record a sound to make sure its frequency,bits,size and channels.(I use this method to solve this problem)
I've had something like this happen. Maybe you have the same problem? Try using an absolute path:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("/absolute_path/desert_rustle.wav")
sounda.play()
Where abslute_path is obviously replaced with your actual absolute path ;)
good luck.
import pygame
pygame.init()
sound = pygame.mixer.Sound("desert_rustle.wav")
pygame.mixer.Sound.play(sound)
This will work on python 3
5 years late answer but I hope I can help someone.. :-)
Firstly, you dont need the "pygame.init()"-line.
Secondly, make a loop and play the sound inside that, or else pygame.mixer will start, and stop playing again immediately.
I got this code to work fine on my Raspberry pi with Raspbian OS.
Note that I used a while-loop that continues to loop the sound forver.
import pygame.mixer
pygame.mixer.init()
sounda = pygame.mixer.Sound("desert_rustle.wav")
while True:
sounda.play()
Just try:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
print ""
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
This should work. You just need to add print ""and the sound will have
had time to load its self.
Many of the posts are running all of this at toplevel, which is why the sound may seem to close. The final method will return while the sound is playing, which closes the program/terminal/process (depending on how called).
What you will eventually want is a probably a class that can call either single time playback or a looping function (both will be called, and will play over each other) for background music and single sound effects.
Here is pattern, that uses a different event loop / run context other than Pygame itself, (I am using tkinter root level object and its init method, you will have to look this up for your own use case) once you have either the Pygame.init() runtime or some other, you can call these methods from your own logic, unless you are exiting the entire runtime, each file playback (either single use or looping)
this code covers the init for ONLY mixer (you need to figure our your root context and where the individual calls should be made for playback, at least 1 level inside root context to be able to rely on the main event loop preventing premature exit of sound files, YOU SHOULD NOT NEED TIME.SLEEP() AT ALL (very anti-pattern here).... ALSO whatever context calls the looping forever bg_music, it will probably be some 'level' or 'scene' or similar in your game/app context, when passing from one 'scene' to the next you will probably want to immediately replace the bg_music with the file for next 'scene', and if you need the fine-grained control stopping the sound_effect objects that are set to play once (or N times)....
from pygame import mixer
bg_music = mixer.Channel(0)
sound_effects = mixer.Channel(1)
call either of these from WITHIN your inner logic loops
effect1 = mixer.Sound('Sound_Effects/'+visid+'.ogg')
sound_effects.play(effect1, 0)
sound1 = mixer.sound('path to ogg or wav file')
bg_music.play(sound1, -1) # play object on this channel, looping forever (-1)
do this:
import pygame
pygame.mixer.init()
pygame.mixer.music.load("desert_rustle.wav")
pygame.mixer.music.play(0)
I think that your problem is that the file is a WAV file.
It worked for me with an MP3. This will probably work on python 3.6.

PYTHON rumps program stops responding after subprocess calls another script

I am currently working on a project that contains many system tray utilities on mac osx, one of these utilities is a 'fake friend soundboard' where I am to enable the user to click on the module then select as example "Discord Ping x1" and the program playback a soundfile of the ping.
Im using RUMPS which enables me to add menus to the system tray however when trying to use libraries to play sounds directly through upon the #rumps.clicked, nothing seems to happen
Instead I've programmed it to run another script that can easily play the sound inside another folder containing all the sounds.
When running the script and clicking a sound, it plays the sound exactly as intended,
but then the program stops responding...
Is this something I'm doing wrong with my code or is there another way i could play the sound using this library?
Heres the code:
import rumps
import subprocess
class sound(rumps.App):
def __init__(self):
super(sound, self).__init__("🔊")
self.menu = ["Fake friend soundboard",
None,
"Discord Sounds:",
"Ping x1",
"Incoming Call",
"Enter Call",
"Leave Call",
"Mute",
"Deafen",
None,
"Skype Sounds:",
"Incoming Call",
None,
"Random:",
"okbuddyretard",
None]
#rumps.clicked("Ping x1")
def about(sender):
subprocess.run("python3 soundboard/discord_pingx1.py", shell=True)
if __name__ == "__main__":
sound().run()
In the soundboard folder there is the sounds folder containing the discord folder containing **
discord_ping.wav
The soundboard folder also hold the discordd_pingx1.py script which is below.
import pyglet
def sound():
sound = pyglet.resource.media('sounds/discord/discord_ping.wav', streaming=False)
sound.play()
pyglet.app.run()
sound()
after running my main.py (opens all the modules)
and clicking the sound tab and then clicking the button set to make the sound,
it plays, but then stops responding.
Any help at all would be much appreciated.
I highly recommend avoiding the insert of subprocess or sys-calls inside of a Python script that executes Objective-C code. This leads to Aborts and Traps. Instead, refer to Apple's APIs and utilize AppleScript (osascript).
Here is a better implementation that calls a script to call your script from osascript:
exec.py
import platform
import subprocess, sys, os
applescript = '''\
do shell script "bash /path/to/file/myShellScript.sh"\
'''
# parse and stdout
args = [item for x in [("-e",l.strip()) for l in applescript.split('\n') if l.strip() != ''] for item in x]
proc = subprocess.Popen(["osascript"] + args ,stdout=subprocess.PIPE )
progname = proc.stdout.read().strip()
sys.stdout.write(str(progname))
The parser takes the string with the osascript in it and parses it for a stdout write. Stdout writes are very safe, considering they are handling data from the same thread.
/path/to/file/myShellScript.sh (add the shebang on line 1 as well)
#!/bin/bash
python3 soundboard/discord_pingx1.py
This 100% handles your problem without causing subprocess errors. If you get hung with subprocess, your computer will continue running Python3. If the Application doesn't stop freezing, exit the app by cmd+Space and typing Activity Monitor. Then, find Python3 by cmd+f and typing python3. Click it and press Quit in the top left corner (the X or stop-light symbol).

How to delay the launch of an mp3 file using vlc

from gtts import *
import os
import vlc
def sauvegarde(text,i):
tts = gTTS(text, lang='fr')
tts.save("text"+str(i)+".mp3")
def play(file):
p = vlc.MediaPlayer(file)
p.play()
text = "Salut Santo c\'est Alexis, ton maitre qui te parle"
text2="Bonjour Santo"
sauvegarde(text,1)
sauvegarde(text2,2)
play("text1.mp3")
play("text2.mp3")
os.system("pause")
When I run this code the two .mp3 files that I created previously are being played at the same time. Any ideas how to play the second one after the first is finished?
vlc doesn't seem to have a blocking version of play as far as I can tell, so probably the easiest way to accomplish this is to manually wait for the first mp3 to finish. So to make a blocking version of your play function, try something like this:
import time
def play(file):
p = vlc.MediaPlayer(file)
p.play()
while(p.is_playing()):
time.sleep(0.1)
This will check is p is still playing every 100ms. Only when it is done playing, the play function will return.
Alternatively, you can use vlc.MediaListPlayer and vlc.MediaList to create a playlist containing your mp3's.

About Tkinter python 2.76 on Linux Mint 17.2

I have 2 functions as below:
def select_audio():
os.chdir("/home/norman/songbook")
top1.lower(root)
name=tkFileDialog.askopenfilename()
doit="play " + name
top1.lift(root)
os.system(doit)
def select_video():
os.chdir("/home/norman/Videos")
top2.lower(root)
name=tkFileDialog.askopenfilename()
doit="mpv --fs " + name
top2.lift(root)
os.system(doit)
They are selected from buttons to allow choosing and playing audio files or video files.
They work to some extent.
Videos are in a different directory and at the same level as the audio files.
It doesn't matter which I choose first I see the correct directory so I can play say a video, if after it's finished I choose audio it still shows the video directory.
Similarly if I first choose audio it still shows the audio directory if I select videos.
I have no idea why it does this. I am not an experienced programmer as you can probably tell from the code.
Some suggestions:
Use a raw string to make sure that Python doesn't try to interpret anything following a \ as an escape sequence:
Change os.chdir("/home/norman/whatever") to os.chdir(r"/home/norman/whatever")
It won't solve this problem, but it will avoid you future problems.
For tkFileDialog use the initialdir option:
Change name=tkFileDialog.askopenfilename() to
name=tkFileDialog.askopenfilename(initialdir=r"home/norman/whatever", parent=root)

How to jump around a sound in pygame?

I am trying to make a media player with Pygame because it comes native on raspbian. I'm wondering if there is an easy way to jump around in a song. The API says there is a way to get the current location in the song and the length of the song, but there is no documented way to jump to an arbitrary position. I need to do this in order to scrub in a media player. Or if someone knows of another python library that ports easily to the Raspberry Pi that would be helpful as well. Thank you.
I could only manage it for music, not Sound:
import pygame, time
pygame.mixer.init()
m = pygame.mixer.music
filename = r"C:\Python32\Lib\site-packages\pygame\examples\data\house_lo.ogg"
m.load(filename)
print("Playing " + filename)
m.play(0, 0)
time.sleep(1)
print("Stopping at {}".format(m.get_pos() / 1000.0))
m.stop()
#time.sleep(0.5)
print("Playing after seek")
m.play(0, 3)
time.sleep(5)

Resources