Created
July 26, 2018 22:00
-
-
Save adammhaile/de17a848334d218f7eaf4963fb2d229d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy | |
import scipy.signal | |
import pygame, pygame.sndarray | |
def play_for(sample_wave, ms): | |
"""Play the given NumPy array, as a sound, for ms milliseconds.""" | |
sound = pygame.sndarray.make_sound(sample_wave) | |
sound.play(-1) | |
pygame.time.delay(ms) | |
sound.stop() | |
sample_rate = 44100 | |
def sine_wave(hz, peak=8192, n_samples=sample_rate): | |
"""Compute N samples of a sine wave with given frequency and peak amplitude. | |
Defaults to one second. | |
""" | |
length = sample_rate / float(hz) | |
omega = numpy.pi * 2 / length | |
xvalues = numpy.arange(int(length)) * omega | |
onecycle = peak * numpy.sin(xvalues) | |
return numpy.resize(onecycle, (n_samples,)).astype(numpy.int16) | |
def square_wave(hz, peak=8192, duty_cycle=.1, n_samples=sample_rate): | |
"""Compute N samples of a sine wave with given frequency and peak amplitude. | |
Defaults to one second. | |
""" | |
t = numpy.linspace(0, 1, 500 * 440/hz, endpoint=False) | |
wave = scipy.signal.square(2 * numpy.pi * 5 * t, duty=duty_cycle) | |
wave = numpy.resize(wave, (n_samples,)) | |
return (peak / 2 * wave.astype(numpy.int16)).astype(numpy.int16) | |
pygame.mixer.init(channels=1) | |
# Play A (440Hz) for 1 second as a sine wave: | |
play_for(sine_wave(440), 1000) | |
# Play A-440 for 1 second as a square wave: | |
play_for(square_wave(440), 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment