I am looking for a way to see if a pygame.mixer.Channel is currently playing a sound. So for example do something only after the sound played in a specific channel has finished. Here is my current code to just play the sound:
import pygame
pygame.mixer.pre_init()
pygame.mixer.init()
pygame.init()
pygame.mixer.Channel(0).play(pygame.mixer.Sound('coolsound.wav'), maxtime=2000)
I was thinking an if statement something like this:
if pygame.mixer.Channel(0) = playing a sound:
print("playing a sound")
else:
print("not playing")
Obviously this wouldn't work, just to give you an idea of what I am looking for.
Thanks!
I got my answer. Using get_busy() I am able to check wether a channel is playing a sound or not, it returns True or False. Here was my final code:
if pygame.mixer.Channel(0).get_busy() == True:
print("playing a sound")
else:
print("not playing")
Here is a link to the documentation for more information: https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.get_busy
Related
I'm trying to play a sound with the pygame.midi module. Here is the code I
use :
#!/usr/bin/env python
import pygame.midi
import time
pygame.midi.init()
print pygame.midi.get_default_output_id()
print pygame.midi.get_device_info(0)
player = pygame.midi.Output(0)
player.set_instrument(0)
print 'Playing...'
player.note_on(64)
time.sleep(1)
player.note_off(64)
print 'Played'
pygame.midi.quit()
I've found similar codes while searching for exemples, here is the output :
0
('ALSA', 'Midi Through Port-0', 0, 1, 0)
Playing...
Played
PortMidi call failed...
PortMidi: `Bad pointer'
type ENTER...
No sound is played, and I didn't find any info about the PortMidi error which
occurs surprisingly after pygame.midi quits.
Do you have any idea? I'm running an debian-based linux distribution if that
can help.
There are two small problems. The sound is not played because you don't set the velocity of the note. Try setting it to 127 (maximum) to hear the sound. The other problem is that you don't delete the midi output object at the end before quitting. This leads to the "PortMidi: `Bad pointer'" error at the end. So here is the corrected code that should work properly:
import pygame.midi
import time
pygame.midi.init()
player = pygame.midi.Output(0)
player.set_instrument(0)
player.note_on(64, 127)
time.sleep(1)
player.note_off(64, 127)
del player
pygame.midi.quit()
thanks for your code, helped me to start with midi and python.
It seems to me you forgot the velocity (sort of volume) information in the note_on, note_off events. The default value is 0, so the note would 'play', but would not be audible.
About the quit error message you get... I can't help, i dont know about Linux and ALSA. For reference, this worked fine for me in a Win Vista box using the default midi mapper. This simply plays either a note, an arpeggio or a chord, using a base note and a major chord structure.
import pygame
import time
import pygame.midi
pygame.midi.init()
player= pygame.midi.Output(0)
player.set_instrument(48,1)
major=[0,4,7,12]
def go(note):
player.note_on(note, 127,1)
time.sleep(1)
player.note_off(note,127,1)
def arp(base,ints):
for n in ints:
go(base+n)
def chord(base, ints):
player.note_on(base,127,1)
player.note_on(base+ints[1],127,1)
player.note_on(base+ints[2],127,1)
player.note_on(base+ints[3],127,1)
time.sleep(1)
player.note_off(base,127,1)
player.note_off(base+ints[1],127,1)
player.note_off(base+ints[2],127,1)
player.note_off(base+ints[3],127,1)
def end():
pygame.quit()
To use it, just import the module and, for example, type a command like go(60), chord (60, major) or arp(60, major)
The error message shows that your output device is a "MIDI Through Port" - which isn't capable of making sounds on it's own. You would have to connect it (e.g. using qjackctl or any other tool letting you connect ALSA MIDI ports) to a software synthesizer like qsynth.
Try importing the entire pygame module:
import pygame
not
import pygame.midi
I am communicating with a Fona 808 module from a Raspberry Pi and I can issue AT commands, yey!
Now I want to make a python program where I can reliably issue AT commands using shortcut commands like "b" for getting the battery level and so on.
This is what I have so far:
import serial
con = serial.Serial('/dev/ttyAMA0',timeout=0.2,baudraute=115200)
def sendAtCommand(command):
if command == 'b':
con.write("at+cbc\n".encode())
reply = ''
while con.inWaiting():
reply = reply + con.read(1)
return reply
while True:
x = raw_input("At command: ")
if x.strip() == 'q':
break
reply = sendAtCommand(x)
print(reply)
con.close()
In the sendAtCommand I will have a bunch of if statements that send different at commands depending on the input it receives.
This is somewhat working but is very unreliable. Sometimes I get the full message. Other times I get nothing. Then double message next time and so on.
I would like to create one method that issues a command to the Fona module and then reads the full response and returns it.
Any suggestions?
Your loop quits if the 'modem' has not responded anything to your at command yet. You should keep reading the serial input until you get a linefeed or until a certain time has passes e.g. 1 second or so.
Okay. It turns out this is pretty trivial.
Since at commands always return OK after a successful query then it is simply a matter of reading the lines until eventually one of them will contain 'OK\r\n'.
Like so:
def readUntilOK():
reply=''
while True:
x = con.readline()
reply += x
if x == 'OK\r\n':
return reply
This does not have a timeout and it does not check for anything else than an OK response. Which makes it very limiting. Adding error handling is up to the reader. Something like if x == 'ERROR\r\n' would be a good start.
Cheers!
I am trying to find a Speech recognition library similar to PySpeech that will work on a Raspberry Pi 2. I am new to this and have tried researching but there are so many applications I just need help choosing the correct one.
All I am trying to do is, when a user says something the program will recognize keywords and open up the correct part of my code which will just display information about that keyword.
Right now I am using Python 2.7 and PyQt4 to display what I want but am willing to change if there is something easier such as KivyPi, PyGame, etc.
I am up for any ideas or any help to push me into the right direction.
Thank You!
I created a library called SpeakPython that helps Python developers do exactly this, and just released it under GPL3. The library is built upon pocketsphinx (sphinxbase) and gstreamer (for streaming recognition, which leads to fast results). It will allow you to attach python code to speech commands.
It's very accurate and dynamic for command parsing such as this, and I've tested it on the Pi already. Let me know if you have any issues.
To recognize few words on Raspberry Pi 2 with Python you can use Python bindings to Pocketsphinx
You can find pocketsphinx tutorial to get started here.
You can find some installation details for RPi here.
You can find code example here.
You can find already functioning example using pocketsphinx and python here.
Here is what I have up and running on my pi, it uses python speech recognition, pyaudio and pythons espeak for voice response (if you want that, if not just take it out) this will listen for voice input, print it to text and speak it back to you.. You can manipulate this to do whatever you want basically -
import pyaudio
from subprocess import call
import speech_recognition
r = sr.Recognizer()
r.energy_threshold=4000
with sr.Microphone(device_index = 2, sample_rate = 44100, chunk_size = 512) as source:
print 'listening..'
audio = r.listen(source)
print 'processing'
try:
message = (r.recognize_google(audio, language = 'en-us', show_all=False))
call(["espeak", message])
except:
call(['espeak', 'Could not understand you'])
First of all, excusme for my bad English. I am working in it.
I am working in a computer vision application. I am using a webcam. The main loop is like this:
while true
get frame
process frame
show frame in figure
end while
And I want something like this:
while figure is open
get frame
process frame
show frame in figure
end while
I used to use figure and imshow for plot the frame, and I used handlers for knowing when the figure is closed by the user.
fig = figure;
set(fig,'KeyPressFcn','exit = true;');
set(fig,'CloseRequestFcn', 'exit = true; delete(gcf)');
But now I am using the vision.VideoPlayer from the Computer System Toolbox because is faster, and I can not find a way to do some similar. I don't want to use a GUI.
The code is this (from this other thread):
vid = videoinput('winvideo', 1, 'RGB24_320x240'); %select input device
hvpc = vision.VideoPlayer; %create video player object
src = getselectedsource(vid);
vid.FramesPerTrigger =1;
vid.TriggerRepeat = Inf;
vid.ReturnedColorspace = 'rgb';
src.FrameRate = '30';
start(vid)
%start main loop for image acquisition
for t=1:500
imgO=getdata(vid,1,'uint8'); %get image from camera
hvpc.step(imgO); %see current image in player
end
Some idea?
You can find the figure handle of vision.VideoPlayer object by turning on "ShowHiddenHandles".
set(0, 'ShowHiddenHandles', 'on') % Revert this back to off after you get the handle
After this gcf can give you the handle. But it is risky to change callbacks for hidden handles. They might already have many of their callbacks set for proper functioning of VideoPlayer object. You might want to check for their validity and visibility to detect whether it is open.
h = gcf;
...
ishandle(h)
get(h, 'Visible') % will return 'off' if the figure is not visible.
I implemented a basic script to play a song using pyglet. However, I get an error and the control does not return to the Command Line and I have to Ctrl+C out of it. What might be happening here?
My code is :
import pyglet
song = pyglet.resource.media('g.wav', streaming = False)
song.play()
pyglet.app.run()
pyglet.app.exit()
I simply get the following :
AL lib: pulseaudio.c:331: PulseAudio returned minreq > tlength/2; expect break up
OpenGL Warning: Failed to connect to host. Make sure 3D acceleration is enabled for this VM.
And the control does not return.
However, when I add :
win = pyglet.window.Window()
Then I get a Window that I can close and then the playback stops.
Can someone tell me how I can implement a piece of code here that plays the file when I run and after playing, returns the command back to the command line?
You can use this code to play the sound and go back to the command line.
import pyglet
music = pyglet.resource.media('sound.wav')
music.play()
def exit_callback(dt):
pyglet.app.exit()
pyglet.clock.schedule_once(exit_callback , music.duration)
pyglet.app.run()
For more information about how this works you can read this other question:
Pyglet sound playing on python