Using pygame midi module [duplicate] - python-2.7

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

Related

Check If A PyGame Mixer Channel Is Playing A Sound

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

Python speech recognition for Raspberry Pi 2

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'])

Python multiprocessing stops

I am a novice user of a cluster running in RedHat Enterprise Linux. I run python script (version 2.6.5) by using bsub command. Somehow this python program just stops during the multiprocessing. The program goes like:
from multiprocessing import Pool
import multiprocessing
def pop_genomics(chrom):
os.system('run analysis on DNA')
os.system('run analysis on DNA')
os.system('run analysis on DNA')
os.system('run analysis on DNA')
print 'Finished!'
return 'Done'
pool = multiprocessing.Pool(multiprocessing.cpu_count())
finalfiledirs=pool.map(pop_genomics, chroms)
pool.close()
pool.join()
I get 'Finished!' message from all workers, but this program does not proceed beyond that 'finalfiledirs=pool.map(pop_genomics, chroms)' line. Can you suggest why this is happening?
You should be getting an error on that line because on the
pool.map(pop_genomics,chroms)
you never pass any parameters to pop_genomics, so you need to add some so it would be:
pool.map(pop_genomics(parameters),chroms)

pyglet - Why does the player not return to the command line?

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

Loading an image using Pyglet

I am playing around with pyglet 1.2alpha-1 and Python 3.3. I have the following (extremely simple) application and cannot figure out what my issue is:
import pyglet
window = pyglet.window.Window()
#image = pyglet.resource.image('img1.jpg')
image = pyglet.image.load('img1.jpg')
label = pyglet.text.Label('Hello, World!!',
font_name='Times New Roman',
font_size=36,
x=window.width//2, y=window.height//2,
anchor_x='center', anchor_y='center')
#window.event
def on_draw():
window.clear()
label.draw()
# image.blit(0,0)
pyglet.app.run()
With the above code, my text label will appear as long as image.blit(0, 0) is commented out. However, if I try to display the image, the program crashes with the following error:
File "C:\Python33\lib\site-packages\pyglet\gl\lib.py", line 105, in errcheck
raise GLException(msg)
pyglet.gl.lib.GLException: b'invalid value'
I also get the above error if I try to use pyglet.resource.image instead of pyglet.image.load (the image and py file are in the same directory).
Any one know how I can fix this issue?
I am using Python 3.3, pyglet 1.2alpha-1, and Windows 8.
The code -including the image.blit- runs fine for me. I'm using python 2.7.3, pyglet 1.1.4
There's nothing wrong with the code. You might consider trying other python and pyglet versions for the time being (until pyglet has a new stable release)
This isn't a "fix", but might at least determine if it's fixable or not (mine was not). (From the Pyglet mailing group.)
You can verify whether the system does not even support Textures greater than 1024, by running this code (Python 3+):
from ctypes import c_long
from pyglet.gl import glGetIntegerv, GL_MAX_TEXTURE_SIZE
i = c_long()
glGetIntegerv(GL_MAX_TEXTURE_SIZE, i)
print (i) # output: c_long(1024) (or higher)
That is the maximum texture size your system supports. If it's 1024, then any larger pictures will raise an Exception. (And the only fix is, get a better system).