How do I get inputs from a MIDI device through Pygame? - python

I'm somewhat new to both Python and Pygame, and trying to simply read MIDI controls live from a Windows computer. I've looked into Pygame and have set up what I think to be most of the right syntaxes, but the shell seems to crash or at least reset at the line pygame.midi.Input(input_id) every time.
import pygame.midi
import time
pygame.init()
pygame.midi.init()
print("The default input device number is " + str(pygame.midi.get_default_input_id()))
input_id = int(pygame.midi.get_default_input_id())
clock = pygame.time.Clock()
crashed = False
while (crashed == False):
print("input:")
pygame.midi.Input(input_id)
print(str(pygame.midi.Input.read(10)))
clock.tick(2)

I am also new to both Python and and Pygame.
I also tried for quite some time to get the midi input reading to work. In another forum I was pointed to an included sample file in the library. You can see the answer here.
Side note:
On my computer there are several Midi devices active. So it maybe would be a good idea to not rely on the default input id. You can get a list of your Midi devices like this:
import pygame
from pygame.locals import *
from pygame import midi
def printMIDIDeviceList():
for i in range(pygame.midi.get_count()):
print(pygame.midi.get_device_info(i), i)

Related

|src/libmpg123/id3.c:559| error: No extra frame text / valid description? [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.

heroku pygame.error:Failed loading libasound.so.2 [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.

How would I be able to pan a sound in pygame?

Basically, what I want to accomplish here, is a way to pan the sound while the game is running. I'd like to make the volumes (left and right) change depending on the position of the player. For now I've got a simple code that I thought that would be a good test:
pygame.mixer.init()
self.sound = pygame.mixer.Sound("System Of A Down - DDevil #06.mp3")
print("I could get here")
self.music = self.sound.play()
self.music.set_volume(1.0, 0)
First, I tried something similar but with pygame.mixer.music, but I came to realize that there's no way to change the volumes separately this way, or so I think, then I changed to the code presented here.
Now it seems like the file is not able to be loaded, my guess is that the file is too big to be treated as a sound in pygame. Any idea of how I'd be able to make this work?
You can pan on the Channel like this:
from os import split, join
import pygame
import pygame.examples.aliens
pygame.init()
# get path to an example punch.wav file that comes with pygame.
sound_path = join(split(pygame.examples.aliens.__file__)[0], 'data', 'punch.wav')
sound = pygame.mixer.Sound(sound_path)
# mixer can mix several sounds together at once.
# Find a free channel to play the sound on.
channel = pygame.mixer.find_channel()
# pan volume full loudness on the left, and silent on right.
channel.set_volume(1.0, 0.0)
channel.play(sound)
https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Channel
It may be worth looking into a seperate audio library for this. In general i'd recommend PortAudio (which is C), but using the python bindings for it provided by PyAudio. This will give you much more control over the exact audio stream.
To simplify this even further, there is a library known as PyDub which is built ontop of PyAudio for a high level interface (it even has a specific pan method!).
from pydub import AudioSegment
from pydub.playback import play
backgroundMusic = AudioSegment.from_wav("music.wav")
# pan the audio 15% to the right
panned_right = backgroundMusic.pan(+0.15)
# pan the audio 50% to the left
panned_left = backgroundMusic.pan(-0.50)
#Play audio
while True:
try:
play(panned_left)
#play(panned_right)
If this is too slow or doesn't provide effective real-time implementations then I would definately give PyAudio a go because you will also learn a lot more about audio processing in the process!
PS. if you do use PyAudio make sure to check out the callback techniques so that the game you are running can continue to run in parallel using different threads.
This answer certainly can help you.
Basically, you get the screen width, then you pan the left according to player.pos.x / screen_width, and the right according to 1 - player.pos.y / screen_width like that:
Pseudocode:
channel = music.play() # we will pan the music through the use of a channel
screen_width = screen.get_surface().get_width()
[main loop]:
right = player.pos.x / screen_width
left = player.pos.x / screen_width
channel.set_volume(left, right)
Documentation:
pygame.mixer.Channel
pygame.mixer.Sound
pygame.mixer.Channel.set_volume

Music player for Python not working

I want to be able to play multiple songs through a playlist using python, but it will only play the last song on the list. Please help.
from pygame import mixer # Load the required library
from os import listdir
k = listdir('C:/LOCAL')
print(k)
mixer.init()
for x in k:
y = "C:/LOCAL/" + x
print y
mixer.music.queue(y)
mixer.music.load(y)
mixer.music.play()
Your problem is that you assume that playing music with pygame will pause the program until the music is finished - which is not the case. As a result, it tries starting a song, and then it's starting another, and another, etc.
There are a few ways of trying to correct this. You could either:
Use pygame events and "tell" pygame to fire an event when the song finishes (though this requires a display surface (window) to be opened within pygame), or
Detect the length of the song, and sleep for that amount of time (which is more compatible with your current code).
I'm going to assume that you would like to do option 2, since your code works better with it.
To get the length of an MP3 file (I've not tried it with any other types), you could use the Mutagen library.
Some example code to get the length of an MP3 file (in seconds):
from mutagen.mp3 import MP3
tracklength = MP3("/path/to/song.mp3").info.length
Then you could substitute the path with y, and time.sleep for the amount of time returned, before continuing to the next iteration of the loop.
Hope that helps.
(also, you don't need to queue a file before loading it - just load and play)

Find the Length of a Song with Pygame

I'm building an Radio Automation Program, but I can't figure out how to have a timer countdown the number of seconds left in the song. I'm currently using Pygame and don't really want to load another toolkit just for this. So far I can make a timer count up using this:
import pygame
#setup music
track = "Music/Track02.wav"
pygame.mixer.music.load(track)
pygame.mixer.music.play()
print("Playing Music")
while(pygame.mixer.music.get_busy()):
print "\r"+str(pygame.mixer.music.get_pos()),
But I have no idea how to get the total length of the song and countdown without having played the song already.
You could also load the song as a normal sound and then check the length while using mixer.music for playing it.
a = pygame.mixer.Sound("test.wav")
print("length",a.get_length())
The mutagen.mp3 can be used to find the length of music.
Firstly: pip install mutagen
-> İmport:
from pygame import *
from mutagen.mp3 import MP3
-> Use:
mixer.music.load('example.mp3')
song = MP3('example.mp3')
songLength = song.info.length
Check the Documentation. According to the site, this function returns the length of a sound object in seconds. So, time remaining is simply (pygame.mixer.music.get_length() - pygame.mixer.music.get_pos())*-1.
That way, it displays as a negative number like most time remaining counters do in a music player. Note, I don't have pygame on this computer, so I can't test it. So, check it just to make sure.

Categories

Resources