Exemple #1
0
    class Sound:
        """Generate sound. Requires PyAudio & NumPy."""

        def __init__(self, rate=44100, channels=1):
            # Suppress Jack and ALSA error messages on Linux: https://github.com/rtmrtmrtmrtm/weakmon/blob/master/weakaudio.py
            nullfd = os.open("/dev/null", 1)
            oerr = os.dup(2)
            os.dup2(nullfd, 2)
            self.stream = PyAudio().open(format=paFloat32, channels=channels, rate=rate, output=True)
            os.dup2(oerr, 2)
            os.close(oerr)
            os.close(nullfd)
            return

        def play(self, frequency=440, length=1.0, volume=1.0, rate=44100):
            """Play sine wave at frequency, for length, at rate parameters values."""
            self.stream.stop_stream()
            self.stream.start_stream()
            wave = concatenate(
                [sin(arange(length * rate) * frequency * pi * 2 / rate)]) * volume
            self.stream.write(wave.astype(float32).tostring())
            return
Exemple #2
0
class Audio:
    def __init__(self):
        self.RATE = 44100
        self.BPM = 100
        self.L1 = (60 / self.BPM * 4) * self.RATE
        self.L2 = self.L1 / 2
        self.L4 = self.L1 / 4
        self.L8 = self.L1 / 8
        self.stream = None

    def open(self):
        self.stream = PyAudio().open(format=paFloat32,
                                     channels=1,
                                     rate=self.RATE,
                                     frames_per_buffer=1024,
                                     output=True)

    def play(self, freq, length):
        t = float(freq) * np.pi * 2 / self.RATE
        s = np.sin(np.arange(length) * t)
        self.stream.write(s.astype(np.float32).tostring())

    def close(self):
        self.stream.close()