Last active
December 21, 2015 22:58
-
-
Save jeffa/6378640 to your computer and use it in GitHub Desktop.
Demonstration of Nyquist's Theorem.
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
use strict; | |
use warnings; | |
use Audio::Wav; | |
use Math::Complex; | |
use constant TWO_PI => pi() * 2; | |
my $wav = Audio::Wav->new(); | |
my $sample_rate = 44100; | |
my $bits_sample = 16; | |
write_out( 'nyquist_good.wav', 8000, 2 ); | |
write_out( 'nyquist_bad.wav', 36000, 2 ); | |
sub write_out { | |
my $filename = shift; | |
my $write = $wav->write($filename, { | |
bits_sample => $bits_sample, | |
sample_rate => $sample_rate, | |
channels => 1, | |
}); | |
add_sine( $write, @_ ); | |
$write->finish(); | |
} | |
sub add_sine { | |
my ($write,$hz,$length) = @_; | |
my $max_no = (2 ** $bits_sample) / 2; | |
$length *= $sample_rate; | |
for my $pos (0..$length) { | |
my $time = ($pos / $sample_rate) * $hz; | |
my $val = sin(TWO_PI * $time); | |
my $samp = $val * $max_no; | |
$write->write($samp); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment