This uses Audio::Wav to create a WAV file of DTMF tones. If you are running Windows, you have the option of playing the file after creating it (just add a second command line parameter of 1). I found the required calculations here and modified the example script listed in the Audio::Wav docs.
Usage: $0 [DTMF tones] [play]
i.e. dtmf.pl 18005551212 1
#!/usr/bin/perl -w use strict; use Audio::Wav; my @tones; my %dtmf = ( '1' => [ 697, 1209 ], '2' => [ 697, 1336 ], '3' => [ 697, 1477 ], 'A' => [ 697, 1633 ], '4' => [ 770, 1209 ], '5' => [ 770, 1336 ], '6' => [ 770, 1477 ], 'B' => [ 770, 1633 ], '7' => [ 852, 1209 ], '8' => [ 852, 1336 ], '9' => [ 852, 1477 ], 'C' => [ 852, 1633 ], '*' => [ 941, 1209 ], '0' => [ 941, 1336 ], '#' => [ 941, 1477 ], 'D' => [ 941, 1633 ], ); if (@ARGV > 0) { @tones = split'',$ARGV[0]; } else { @tones = sort keys %dtmf; } my $play = $ARGV[1] || 0; my $sample_rate = 8000; my $bits_sample = 8; my $num_channels = 1; my $pi = 4 * atan2 1, 1; my $duration = 0.5 * $sample_rate; my $wav = new Audio::Wav; my $details = { 'bits_sample' => $bits_sample, 'sample_rate' => $sample_rate, 'channels' => $num_channels, }; my $write = $wav -> write( 'dtmf.wav', $details ); for my $tone (@tones) { my @hz = map { 2 * $pi * $_ } @{$dtmf{$tone}}; add_tone(@hz); } $write -> finish(); Win32::Sound::Play('dtmf.wav') if $play && $main::can_play; sub add_tone { my (@hz) = @_; for my $pos ( 0 .. $duration ) { my $time = $pos / $sample_rate; my $val = 63 * sin($time * $hz[0]) + 63 * sin($time * $hz[1]); $write -> write( $val ); } } BEGIN { if ($^O =~ /MSWin32/) { require Win32::Sound; our $can_play = 1; } }
Update: Moved some of the calculations outside of the subroutine. Adjusted the calculation of pi.
Updated much, much later: I really don't know if the tones produced are indeed at the right frequencies... It sounds right to me but I'm no expert.
Third update: Fixed the formula as pointed out in arhuman's reply.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: DTMF Tone Generator
by zengargoyle (Deacon) on Feb 21, 2003 at 22:03 UTC | |
by Coruscate (Sexton) on Mar 20, 2003 at 23:22 UTC | |
Re: DTMF Tone Generator
by hardburn (Abbot) on Feb 22, 2003 at 04:32 UTC | |
Re: DTMF Tone Generator
by grantm (Parson) on Feb 22, 2003 at 03:24 UTC | |
by Mr_Person (Hermit) on Feb 22, 2003 at 17:13 UTC | |
by zengargoyle (Deacon) on Feb 22, 2003 at 17:44 UTC | |
Re: DTMF Tone Generator
by arhuman (Vicar) on Jun 27, 2003 at 13:02 UTC | |
by Mr. Muskrat (Canon) on Jun 27, 2003 at 14:27 UTC | |
Re: DTMF Tone Generator
by Anonymous Monk on Jun 20, 2008 at 04:25 UTC | |
Re: DTMF Tone Generator
by Anonymous Monk on Dec 14, 2009 at 09:15 UTC | |
Re: DTMF Tone Generator
by smichal (Initiate) on Aug 16, 2012 at 21:46 UTC | |
by roboticus (Chancellor) on Aug 16, 2012 at 23:59 UTC | |
by Mr. Muskrat (Canon) on Aug 17, 2012 at 17:34 UTC |
Back to
Cool Uses for Perl