Any ideas why the code below does not play the sound? If the s.play() were to be outside the clock() function, it work.
import time
import pygame
pygame.init()
s = pygame.mixer.Sound("0614.wav")
def clock ():
x = input("How long to start the alarm for? ")
delay = float(x)
print ("Alarm Started")
time.sleep(delay)
print ("!!!!ALARM!!!!!")
s.play()
clock()
Is your file "0614.wav" in the same folder as form the program is executed?.
To see the error use try-except block and then print the error.
Related
The question pure and simple. I've tried using while loops, rearranging code, but all that happens is that the program starts when i press the button or does absolutely nothing at all. Can anyone see what I am doing wrong?
#!/usr/bin/env python3
from ev3dev2.motor import MoveTank, OUTPUT_B, OUTPUT_C
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from time import sleep
import time
sound = Sound()
btn = Button()
tank_pair = MoveTank(OUTPUT_B, OUTPUT_C)
def movement(left_speed, right_speed, rotations):
tank_pair.on_for_rotations(left_speed, right_speed, rotations, brake=True, block=True)
while not btn.any():
movement(20,20,10)
movement(-100,0,1.5)
movement(20,20,10)
sleep(0.01)
while btn.any():
sleep(0.01)
tank_pair.off()
sound.beep()
exit()
you can break your main loop using this
pip install keyboard
then
import keyboard
while True:
# do something
if keyboard.is_pressed("q"):
print("q pressed, ending loop")
break
Your indentation is incorrect.
from ev3dev2.motor import MoveTank, OUTPUT_B, OUTPUT_C
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from time import sleep
import time
sound = Sound()
btn = Button()
tank_pair = MoveTank(OUTPUT_B, OUTPUT_C)
def movement(left_speed, right_speed, rotations):
tank_pair.on_for_rotations(left_speed, right_speed, rotations, brake=True, block=True)
while not btn.any():
movement(20,20,10)
movement(-100,0,1.5)
movement(20,20,10)
sleep(0.01)
while btn.any():
sleep(0.01)
tank_pair.off()
sound.beep()
exit()
I've been trying to find a good limited-input-time code for Python scripts and I finally got a code to work:
from threading import Timer
timeout = 5
t = Timer(timeout, print, ["Time's up!"])
t.start()
entry = input('> ')
t.cancel()
but, I need to be able to run a function when the timer ends.
Also - I want the function called inside of the timer code - otherwise if you type your entry before the timer runs out, the function will still be called no matter what.
Could anyone kindly edit this code I have to be able to run a function when the timer ends?
If it is fine that you block the main thread when the user has not provided any answer, the above code that you have shared might work.
Otherwise you could use msvcrt in the following sense:
import msvcrt
import time
class TimeoutExpired(Exception):
pass
def input_with_timeout(prompt, timeout, timer=time.monotonic):
sys.stdout.write(prompt)
sys.stdout.flush()
endtime = timer() + timeout
result = []
while timer() < endtime:
if msvcrt.kbhit():
result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
if result[-1] == '\n': #XXX check what Windows returns here
return ''.join(result[:-1])
time.sleep(0.04) # just to yield to other processes/threads
raise TimeoutExpired
The above code is compliant with Python3 and you will need to test it.
Reading from the Python Documentation https://docs.python.org/3/library/threading.html#timer-objects
I have come up with the following snippet which might work(Try running in your command line prompt)
from threading import Timer
def input_with_timeout(x):
def time_up():
answer= None
print('time up...')
t = Timer(x,time_up) # x is amount of time in seconds
t.start()
try:
answer = input("enter answer : ")
except Exception:
print('pass\n')
answer = None
if answer != True: # it means if variable has something
t.cancel() # time_up will not execute(so, no skip)
input_with_timeout(5) # try this for five seconds
Version of pyglet - 1.4.2. Python - 3.6.6Ubuntu - 18.04
Code example:
import pyglet
import time
pyglet.options['audio'] = ('openal', 'pulse', 'directsound', 'silent')
source = pyglet.media.StaticSource(pyglet.media.load('explosion.wav'))
def my_playlist():
while True:
print(time.time())
print(1)
yield source
player = pyglet.media.Player()
player.queue(my_playlist())
player.play()
pyglet.app.run()
Code was writed based on documentation:
Logs in console:
1566296930.8165386 # played once
1
1566296931.529639 # won't play
1
1566296931.5301056 # won't play and etc.
1
1566296931.5304687
1
1566296931.5309348
1
Expected result:
Audio should play in loop with sounds which is returned from generator.
Current result:
Audio is played once.
Question:
What I did wrong here and how to achive expected result?
Not sure if you're trying to accomplish something more, but if all you need from your loop is to loop sound, you shouldn't actually use a loop of any kind. Instead, use the designated EOS_LOOP flag/trigger.
import pyglet
import time
pyglet.options['audio'] = ('openal', 'pulse', 'directsound', 'silent')
source = pyglet.media.StaticSource(pyglet.media.load('explosion.wav'))
player = pyglet.media.Player()
player.queue(source)
player.EOS_LOOP = 'loop'
player.play()
pyglet.app.run()
And since it's deprecated, you should move away to using the SourceGroup with the loop flag set.
I am trying to create a media player with Python that will play mp3 files one after the other and allow me to play and pause the music at any time (similar to spotify).
I have used the vlc library and pygame music function to play the files, but my problem comes when the song has finished and I want it to play the next file. I have manged to do this but not with a play and pause functionality.
My rough code:
import pygame
import time
#plays first mp3 file
file = '4c68Z9wLdHc36y3CNjwQKM.ogg'
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file)
pygame.mixer.music.play()
#play and pause funtionnality
while pygame.mixer.music.get_busy():
timer = pygame.mixer.music.get_pos()
time.sleep(1)
control = input()
pygame.time.Clock().tick(10)
if control == "pause":
pygame.mixer.music.pause()
elif control == "play" :
pygame.mixer.music.unpause()
elif control == "time":
timer = pygame.mixer.music.get_pos()
timer = timer/1000
print (str(timer))
elif int(timer) > 10:
print ("True")
pygame.mixer.music.stop()
break
else:
pass
#next mp3 file
file = '3qiyyUfYe7CRYLucrPmulD.ogg'
pygame.mixer.music.load(file)
pygame.mixer.music.play()
When I run this my hope is that it will play the first file and allow me to play and pause, but it stops when a song ends and not play the next one, as it gets stuck waiting for an input.
I want it to play the first file, allowing me to pause and resume it at any time, and then when the song has finished, it automatically plays the next file.
Thanks in advance.
To narrow it down I would like to know how to create a while that has a user input that will always check for a condition and not just at the start of the while loop.
I'm not sure why you tagged this question vlc if you are using pygame as arguably vlc.py has this functionallity pretty much built in.
However, all you need to do is use a double while statement.
The first controls the file to be played and the second performs your play/pause control. e.g.
import pygame
import time
files = ['./vp1.mp3','./vp.mp3']
pygame.init()
pygame.mixer.init()
stepper = 0
#file loading
while stepper < len(files):
pygame.mixer.music.load(files[stepper])
print("Playing:",files[stepper])
stepper += 1
pygame.mixer.music.play()
#play and pause
while pygame.mixer.music.get_busy():
timer = pygame.mixer.music.get_pos()
time.sleep(1)
control = input()
pygame.time.Clock().tick(10)
if control == "pause":
pygame.mixer.music.pause()
elif control == "play" :
pygame.mixer.music.unpause()
elif control == "time":
timer = pygame.mixer.music.get_pos()
timer = timer/1000
print (str(timer))
elif int(timer) > 10:
print ("True")
pygame.mixer.music.stop()
break
else:
continue
I was in the process of making a program that simply repeats any text you enter, and seemed to be working when I first tested it. The problem is that the second time I attempt to type anything, it crashes and says that permission was denied to the sound file I was recording it to. I believe it is because the file was already opened, but none the less I do not know how to fix it. I am using the gTTS and Pygame modules.
from gtts import gTTS
from tempfile import TemporaryFile
from pygame import mixer
#Plays Sound
def play():
mixer.init()
mixer.music.load("Speech.mp3")
mixer.music.play()
#Voice
def voice(x):
text = gTTS(text= x, lang= 'en')
with open("Speech.mp3", 'wb') as f:
text.write_to_fp(f)
f.close()
play()
#Prompts user to enter text for speech
while True:
voice_input = input("What should Wellington Say: ")
voice(voice_input)
Figured it out. I added this function:
def delete():
sleep(2)
mixer.music.load("Holder.mp3")
os.remove("Speech.mp3")
And call it after .play(), so it now simply deletes the file when it is done and then re-creates it when you need to use it next.
To expand on my comment above (with help from this thread), I think play() may be locking the file. You can manually try the following:
def play():
mixer.init()
mixer.music.load("Speech.mp3")
mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
or
def play():
mixer.init()
mixer.music.load("Speech.mp3")
mixer.music.play()
mixer.music.stop()
But this second fix might have the consequence of not hearing anything played back.
I fixed the problem by writing to a temporary file and using os.rename:
from gtts import gTTS
from pygame import mixer
import os
play_name = 'Speech.mp3'
save_name = "%s.%s" % (play_name, '.tmp')
def play():
mixer.music.load(play_name)
mixer.music.play()
def voice(x):
text = gTTS(text=x, lang='en')
with open(save_name, 'wb') as tmp_file:
text.write_to_fp(tmp_file)
os.rename(save_name, play_name)
try:
mixer.init()
while True:
voice_input = raw_input("What should Wellington Say: ")
voice(voice_input)
play()
except KeyboardInterrupt:
pass
I ran a test where I typed in a very long sentence and then another sentence while the first one was playing and everything still worked.