I'm doing a project with an embedded computer module, the EXM32 Starter Kit and I want to simulate a piano with 8 musical notes. The OS is linux and I'm programming in Python. My problem is that version of Python is the 2.4 without 'pygame' library to play two sounds simultaneously. At now I am using in python "os.system('aplay ./Do.wav')" to play, from linux console, the sound.
The simplificated question is: Can I use another library to do the same as:
snd1 = pygame.mixer.Sound('./Do.wav')
snd2 = pygame.mixer.Sound('./Re.wav')
snd1.play()
snd2.play()
to play 'Do' and 'Re' simultanously? I can use "auidoop" and "wave" library.
I tried use threading but the problem is that the program wait until the console command has been finished. Another library that can I used? or the method to do with 'wave' or 'audioop'?? (this last library I believe is only for manipulated sound files) The complete code is:
import termios, sys, os, time
TERMIOS = termios
#I wrote this method to simulate keyevent. I haven't got better libraries to do this
def getkey():
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
new[6][TERMIOS.VMIN] = 1
new[6][TERMIOS.VTIME] = 0
termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
key_pressed = None
try:
key_pressed = os.read(fd, 1)
finally:
termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
return key_pressed
def keyspress(note):
if note == DO:
os.system('aplay ./notas_musicales/Do.wav')
elif note == RE:
os.system('aplay ./notas_musicales/Re.wav')
elif note == MI:
os.system('aplay ./notas_musicales/Mi.wav')
elif note == FA:
os.system('aplay ./notas_musicales/Fa.wav')
elif note == SOL:
os.system('aplay ./notas_musicales/Sol.wav')
elif note == LA:
os.system('aplay ./notas_musicales/La.wav')
elif note == SI:
os.system('aplay ./notas_musicales/Si.wav')
DO = 'a'
RE = 's'
MI = 'd'
FA = 'f'
SOL = 'g'
LA = 'h'
SI = 'j'
key_pressed = ""
i = 1
#in each iteration the program enter into the other 'if' to doesn't interrupt
#the last sound.
while(key_pressed != 'n'):
key_pressed = getkey()
if i == 1:
keyspress(key_pressed)
i = 0
elif i == 0:
keyspress(key_pressed)
i = 1
print ord(key_pressed)
Due to the global interpreter lock ("GIL") in the default python implementation only one thread will be running at a time. So that won't help you much in this case.
Additionally,
os.system
waits for the command to finish, and spawns an extra shell to run the command in. You should usesuprocess.Popen
instead, which will return as soon as it has started the program, and by default does not spawn an extra shell. The following code should start both players as closely together as possible:Your basic problem is that you want to spawn a process and not wait for its return value. You can't do that with
os.system()
(well you could just spawn dozens of threads).You can do this with the subprocess module which incidentally is available since 2.4. See here for an example.