I found this code for playing sounds: from array import array from time import sleep
Code:
I use this method to for convenience:
Code:
Putting -1 for ms plays the sound infinitely.
My problem is that I have no way of controlling when the sound stops. I have tried playing another inaudible frequency over it, but both can play at the same time. Any ideas on how to end the playing of the sound upon releasing the key?
Code:
import pygame
from pygame.mixer import Sound, get_init, pre_init
class Note(Sound):
def __init__(self, frequency, volume=.1):
self.frequency = frequency
Sound.__init__(self, self.build_samples())
self.set_volume(volume)
def build_samples(self):
period = int(round(get_init()[0] / self.frequency))
samples = array("h", [0] * period)
amplitude = 2 ** (abs(get_init()[1]) - 1) - 1
for time in range(period):
if time < period / 2:
samples[time] = amplitude
else:
samples[time] = -amplitude
return samples
if __name__ == "__main__":
pre_init(44100, -16, 1, 1024)
pygame.init()
Note(440).play(-1)
sleep(5)
I use this method to for convenience:
Code:
def playSound(hz,ms):
pre_init(44100, -16, 1, 1024)
Note(hz).play(ms)
Putting -1 for ms plays the sound infinitely.
My problem is that I have no way of controlling when the sound stops. I have tried playing another inaudible frequency over it, but both can play at the same time. Any ideas on how to end the playing of the sound upon releasing the key?