home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _a4a6cd42f09b12a4ef98ad3f92530fee < prev    next >
Text File  |  2004-06-01  |  15KB  |  583 lines

  1. #######################################################################
  2. #
  3. # Win32::Sound - An extension to play with Windows sounds
  4. # Author: Aldo Calpini <dada@divinf.it>
  5. # Version: 0.47
  6. # Info:
  7. #       http://www.divinf.it/dada/perl
  8. #       http://www.perl.com/CPAN/authors/Aldo_Calpini
  9. #
  10. #######################################################################
  11. # Version history: 
  12. # 0.01 (19 Nov 1996) file created
  13. # 0.03 (08 Apr 1997) first release
  14. # 0.30 (20 Oct 1998) added Volume/Format/Devices/DeviceInfo
  15. #                    (thanks Dave Roth!)
  16. # 0.40 (16 Mar 1999) added the WaveOut object
  17. # 0.45 (09 Apr 1999) added $! support, documentation et goodies
  18. # 0.46 (25 Sep 1999) fixed small bug in DESTROY, wo was used without being
  19. #             initialized (Gurusamy Sarathy <gsar@activestate.com>)
  20. # 0.47 (22 May 2000) support for passing Unicode string to Play()
  21. #                    (Doug Lankshear <dougl@activestate.com>)
  22.  
  23. package Win32::Sound;
  24.  
  25. # See the bottom of this file for the POD documentation.  
  26. # Search for the string '=head'.
  27.  
  28. require Exporter;       # to export the constants to the main:: space
  29. require DynaLoader;     # to dynuhlode the module.
  30.  
  31. @ISA= qw( Exporter DynaLoader );
  32. @EXPORT = qw(
  33.     SND_ASYNC
  34.     SND_NODEFAULT
  35.     SND_LOOP
  36.     SND_NOSTOP
  37. );
  38.  
  39. #######################################################################
  40. # This AUTOLOAD is used to 'autoload' constants from the constant()
  41. # XS function.  If a constant is not found then control is passed
  42. # to the AUTOLOAD in AutoLoader.
  43. #
  44.  
  45. sub AUTOLOAD {
  46.     my($constname);
  47.     ($constname = $AUTOLOAD) =~ s/.*:://;
  48.     #reset $! to zero to reset any current errors.
  49.     local $! = 0;
  50.     my $val = constant($constname, @_ ? $_[0] : 0);
  51.     if ($! != 0) {
  52.  
  53.     # [dada] This results in an ugly Autoloader error
  54.  
  55.     #if ($! =~ /Invalid/) {
  56.     #    $AutoLoader::AUTOLOAD = $AUTOLOAD;
  57.     #    goto &AutoLoader::AUTOLOAD;
  58.     #} else {
  59.     
  60.     # [dada] ... I prefer this one :)
  61.  
  62.         ($pack, $file, $line) = caller;
  63.         undef $pack; # [dada] and get rid of "used only once" warning...
  64.         die "Win32::Sound::$constname is not defined, used at $file line $line.";
  65.  
  66.     #}
  67.     }
  68.     eval "sub $AUTOLOAD { $val }";
  69.     goto &$AUTOLOAD;
  70. }
  71.  
  72.  
  73. #######################################################################
  74. # STATIC OBJECT PROPERTIES
  75. #
  76. $VERSION="0.47"; 
  77. undef unless $VERSION; # [dada] to avoid "possible typo" warning
  78.  
  79. #######################################################################
  80. # METHODS
  81. #
  82.  
  83. sub Version { $VERSION }
  84.  
  85. sub Volume {
  86.     my(@in) = @_;
  87.     # Allows '0%'..'100%'   
  88.     $in[0] =~ s{ ([\d\.]+)%$ }{ int($1*100/255) }ex if defined $in[0];
  89.     $in[1] =~ s{ ([\d\.]+)%$ }{ int($1*100/255) }ex if defined $in[1];
  90.     _Volume(@in);
  91. }
  92.  
  93. #######################################################################
  94. # dynamically load in the Sound.dll module.
  95. #
  96.  
  97. bootstrap Win32::Sound;
  98.  
  99. #######################################################################
  100. # Win32::Sound::WaveOut
  101. #
  102.  
  103. package Win32::Sound::WaveOut;
  104.  
  105. sub new {
  106.     my($class, $one, $two, $three) = @_;
  107.     my $self = {};
  108.     bless($self, $class);
  109.     
  110.     if($one !~ /^\d+$/ 
  111.     and not defined($two)
  112.     and not defined($three)) {
  113.         # Looks like a file
  114.         $self->Open($one);
  115.     } else {
  116.         # Default format if not given
  117.         $self->{samplerate} = ($one   or 44100);
  118.         $self->{bits}       = ($two   or 16);
  119.         $self->{channels}   = ($three or 2);
  120.         $self->OpenDevice();
  121.     }
  122.     return $self;
  123. }
  124.  
  125. sub Volume {
  126.     my(@in) = @_;
  127.     # Allows '0%'..'100%'   
  128.     $in[0] =~ s{ ([\d\.]+)%$ }{ int($1*255/100) }ex if defined $in[0];
  129.     $in[1] =~ s{ ([\d\.]+)%$ }{ int($1*255/100) }ex if defined $in[1];
  130.     _Volume(@in);
  131. }
  132.  
  133. sub Pitch {
  134.     my($self, $pitch) = @_;
  135.     my($int, $frac);
  136.     if(defined($pitch)) {
  137.         $pitch =~ /(\d+).?(\d+)?/;
  138.         $int = $1;
  139.         $frac = $2 or 0;
  140.         $int = $int << 16;
  141.         $frac = eval("0.$frac * 65536");
  142.         $pitch = $int + $frac;
  143.         return _Pitch($self, $pitch);
  144.     } else {
  145.         $pitch = _Pitch($self);
  146.         $int = ($pitch & 0xFFFF0000) >> 16;
  147.         $frac = $pitch & 0x0000FFFF;
  148.         return eval("$int.$frac");
  149.     }
  150. }
  151.  
  152. sub PlaybackRate {
  153.     my($self, $rate) = @_;
  154.     my($int, $frac);
  155.     if(defined($rate)) {
  156.         $rate =~ /(\d+).?(\d+)?/;
  157.         $int = $1;
  158.         $frac = $2 or 0;
  159.         $int = $int << 16;
  160.         $frac = eval("0.$frac * 65536");
  161.         $rate = $int + $frac;
  162.         return _PlaybackRate($self, $rate);
  163.     } else {
  164.         $rate = _PlaybackRate($self);
  165.         $int = ($rate & 0xFFFF0000) >> 16;
  166.         $frac = $rate & 0x0000FFFF;
  167.         return eval("$int.$frac");
  168.     }
  169. }
  170.  
  171. # Preloaded methods go here.
  172.  
  173. #Currently Autoloading is not implemented in Perl for win32
  174. # Autoload methods go after __END__, and are processed by the autosplit program.
  175.  
  176. 1;
  177. __END__
  178.  
  179.  
  180. =head1 NAME
  181.  
  182. Win32::Sound - An extension to play with Windows sounds
  183.  
  184. =head1 SYNOPSIS
  185.  
  186.     use Win32::Sound;
  187.     Win32::Sound::Volume('100%');
  188.     Win32::Sound::Play("file.wav");
  189.     Win32::Sound::Stop();
  190.     
  191.     # ...and read on for more fun ;-)
  192.  
  193. =head1 FUNCTIONS
  194.  
  195. =over 4
  196.  
  197. =item B<Win32::Sound::Play(SOUND, [FLAGS])>
  198.  
  199. Plays the specified sound: SOUND can the be name of a WAV file
  200. or one of the following predefined sound names:
  201.  
  202.     SystemDefault
  203.     SystemAsterisk
  204.     SystemExclamation
  205.     SystemExit
  206.     SystemHand
  207.     SystemQuestion
  208.     SystemStart
  209.  
  210. Additionally, if the named sound could not be found, the 
  211. function plays the system default sound (unless you specify the 
  212. C<SND_NODEFAULT> flag). If no parameters are given, this function 
  213. stops the sound actually playing (see also Win32::Sound::Stop).
  214.  
  215. FLAGS can be a combination of the following constants:
  216.  
  217. =over 4
  218.  
  219. =item C<SND_ASYNC>
  220.  
  221. The sound is played asynchronously and the function 
  222. returns immediately after beginning the sound
  223. (if this flag is not specified, the sound is
  224. played synchronously and the function returns
  225. when the sound ends).
  226.  
  227. =item C<SND_LOOP>
  228.  
  229. The sound plays repeatedly until it is stopped.
  230. You must also specify C<SND_ASYNC> flag.
  231.  
  232. =item C<SND_NODEFAULT>
  233.  
  234. No default sound is used. If the specified I<sound>
  235. cannot be found, the function returns without
  236. playing anything.
  237.  
  238. =item C<SND_NOSTOP>
  239.  
  240. If a sound is already playing, the function fails.
  241. By default, any new call to the function will stop
  242. previously playing sounds.
  243.  
  244. =back
  245.  
  246. =item B<Win32::Sound::Stop()>
  247.  
  248. Stops the sound currently playing.
  249.  
  250. =item B<Win32::Sound::Volume()>
  251.  
  252. Returns the wave device volume; if 
  253. called in an array context, returns left
  254. and right values. Otherwise, returns a single
  255. 32 bit value (left in the low word, right 
  256. in the high word).
  257. In case of error, returns C<undef> and sets
  258. $!.
  259.  
  260. Examples:
  261.  
  262.     ($L, $R) = Win32::Sound::Volume();
  263.     if( not defined Win32::Sound::Volume() ) {
  264.         die "Can't get volume: $!";
  265.     }
  266.  
  267. =item B<Win32::Sound::Volume(LEFT, [RIGHT])>
  268.  
  269. Sets the wave device volume; if two arguments
  270. are given, sets left and right channels 
  271. independently, otherwise sets them both to
  272. LEFT (eg. RIGHT=LEFT). Values range from
  273. 0 to 65535 (0xFFFF), but they can also be
  274. given as percentage (use a string containing 
  275. a number followed by a percent sign).
  276.  
  277. Returns C<undef> and sets $! in case of error,
  278. a true value if successful.
  279.  
  280. Examples:
  281.  
  282.     Win32::Sound::Volume('50%');
  283.     Win32::Sound::Volume(0xFFFF, 0x7FFF);
  284.     Win32::Sound::Volume('100%', '50%');
  285.     Win32::Sound::Volume(0);
  286.  
  287. =item B<Win32::Sound::Format(filename)>
  288.  
  289. Returns information about the specified WAV file format;
  290. the array contains:
  291.  
  292. =over
  293.  
  294. =item * sample rate (in Hz)
  295.  
  296. =item * bits per sample (8 or 16)
  297.  
  298. =item * channels (1 for mono, 2 for stereo)
  299.  
  300. =back
  301.  
  302. Example:
  303.  
  304.     ($hz, $bits, $channels) 
  305.         = Win32::Sound::Format("file.wav");
  306.  
  307.  
  308. =item B<Win32::Sound::Devices()>
  309.  
  310. Returns all the available sound devices;
  311. their names contain the type of the
  312. device (WAVEOUT, WAVEIN, MIDIOUT,
  313. MIDIIN, AUX or MIXER) and 
  314. a zero-based ID number: valid devices
  315. names are for example:
  316.  
  317.     WAVEOUT0
  318.     WAVEOUT1
  319.     WAVEIN0
  320.     MIDIOUT0
  321.     MIDIIN0
  322.     AUX0
  323.     AUX1
  324.     AUX2
  325.  
  326. There are also two special device
  327. names, C<WAVE_MAPPER> and C<MIDI_MAPPER>
  328. (the default devices for wave output
  329. and midi output).
  330.  
  331. Example:
  332.  
  333.     @devices = Win32::Sound::Devices();
  334.  
  335. =item Win32::Sound::DeviceInfo(DEVICE)
  336.  
  337. Returns an associative array of information 
  338. about the sound device named DEVICE (the
  339. same format of Win32::Sound::Devices).
  340.  
  341. The content of the array depends on the device
  342. type queried. Each device type returns B<at least> 
  343. the following information:
  344.  
  345.     manufacturer_id
  346.     product_id
  347.     name
  348.     driver_version
  349.  
  350. For additional data refer to the following
  351. table:
  352.  
  353.     WAVEIN..... formats
  354.                 channels
  355.     
  356.     WAVEOUT.... formats
  357.                 channels
  358.                 support
  359.                 
  360.     MIDIOUT.... technology
  361.                 voices
  362.                 notes
  363.                 channels
  364.                 support
  365.                 
  366.     AUX........ technology
  367.                 support
  368.                 
  369.     MIXER...... destinations
  370.                 support
  371.  
  372. The meaning of the fields, where not
  373. obvious, can be evinced from the 
  374. Microsoft SDK documentation (too long
  375. to report here, maybe one day... :-).
  376.  
  377. Example:
  378.  
  379.     %info = Win32::Sound::DeviceInfo('WAVE_MAPPER');
  380.     print "$info{name} version $info{driver_version}\n";
  381.  
  382. =back
  383.  
  384. =head1 THE WaveOut PACKAGE
  385.  
  386. Win32::Sound also provides a different, more
  387. powerful approach to wave audio data with its 
  388. C<WaveOut> package. It has methods to load and
  389. then play WAV files, with the additional feature
  390. of specifying the start and end range, so you
  391. can play only a portion of an audio file.
  392.  
  393. Furthermore, it is possible to load arbitrary
  394. binary data to the soundcard to let it play and
  395. save them back into WAV files; in a few words,
  396. you can do some sound synthesis work.
  397.  
  398. =head2 FUNCTIONS
  399.  
  400. =over
  401.  
  402. =item new Win32::Sound::WaveOut(FILENAME)
  403.  
  404. =item new Win32::Sound::WaveOut(SAMPLERATE, BITS, CHANNELS)
  405.  
  406. =item new Win32::Sound::WaveOut()
  407.  
  408. This function creates a C<WaveOut> object; the
  409. first form opens the specified wave file (see
  410. also C<Open()> ), so you can directly C<Play()> it.
  411.  
  412. The second (and third) form opens the
  413. wave output device with the format given
  414. (or if none given, defaults to 44.1kHz,
  415. 16 bits, stereo); to produce something
  416. audible you can either C<Open()> a wave file
  417. or C<Load()> binary data to the soundcard
  418. and then C<Write()> it.
  419.  
  420. =item Close()
  421.  
  422. Closes the wave file currently opened.
  423.  
  424. =item CloseDevice()
  425.  
  426. Closes the wave output device; you can change
  427. format and reopen it with C<OpenDevice()>.
  428.  
  429. =item GetErrorText(ERROR)
  430.  
  431. Returns the error text associated with
  432. the specified ERROR number; note it only
  433. works for wave-output-specific errors.
  434.  
  435. =item Load(DATA)
  436.  
  437. Loads the DATA buffer in the soundcard.
  438. The format of the data buffer depends
  439. on the format used; for example, with
  440. 8 bit mono each sample is one character,
  441. while with 16 bit stereo each sample is
  442. four characters long (two 16 bit values
  443. for left and right channels). The sample
  444. rate defines how much samples are in one
  445. second of sound. For example, to fit one
  446. second at 44.1kHz 16 bit stereo your buffer
  447. must contain 176400 bytes (44100 * 4).
  448.  
  449. =item Open(FILE)
  450.  
  451. Opens the specified wave FILE.
  452.  
  453. =item OpenDevice()
  454.  
  455. Opens the wave output device with the
  456. current sound format (not needed unless
  457. you used C<CloseDevice()>).
  458.  
  459. =item Pause()
  460.  
  461. Pauses the sound currently playing; 
  462. use C<Restart()> to continue playing.
  463.  
  464. =item Play( [FROM, TO] )
  465.  
  466. Plays the opened wave file. You can optionally
  467. specify a FROM - TO range, where FROM and TO
  468. are expressed in samples (or use FROM=0 for the
  469. first sample and TO=-1 for the last sample).
  470. Playback happens always asynchronously, eg. in 
  471. the background.
  472.  
  473. =item Position()
  474.  
  475. Returns the sample number currently playing;
  476. note that the play position is not zeroed
  477. when the sound ends, so you have to call a
  478. C<Reset()> between plays to receive the
  479. correct position in the current sound.
  480.  
  481. =item Reset()
  482.  
  483. Stops playing and resets the play position
  484. (see C<Position()>).
  485.  
  486. =item Restart()
  487.  
  488. Continues playing the sound paused by C<Pause()>.
  489.  
  490. =item Save(FILE, [DATA])
  491.  
  492. Writes the DATA buffer (if not given, uses the 
  493. buffer currently loaded in the soundcard) 
  494. to the specified wave FILE.
  495.  
  496. =item Status()
  497.  
  498. Returns 0 if the soundcard is currently playing,
  499. 1 if it's free, or C<undef> on errors.
  500.  
  501. =item Unload()
  502.  
  503. Frees the soundcard from the loaded data.
  504.  
  505. =item Volume( [LEFT, RIGHT] )
  506.  
  507. Gets or sets the volume for the wave output device.
  508. It works the same way as Win32::Sound::Volume.
  509.  
  510. =item Write()
  511.  
  512. Plays the data currently loaded in the soundcard;
  513. playback happens always asynchronously, eg. in 
  514. the background.
  515.  
  516. =back
  517.  
  518. =head2 THE SOUND FORMAT
  519.  
  520. The sound format is stored in three properties of
  521. the C<WaveOut> object: C<samplerate>, C<bits> and
  522. C<channels>.
  523. If you need to change them without creating a 
  524. new object, you should close before and reopen 
  525. afterwards the device.
  526.  
  527.     $WAV->CloseDevice();
  528.     $WAV->{samplerate} = 44100; # 44.1kHz
  529.     $WAV->{bits}       = 8;     # 8 bit
  530.     $WAV->{channels}   = 1;     # mono
  531.     $WAV->OpenDevice();
  532.  
  533. You can also use the properties to query the
  534. sound format currently used.
  535.  
  536. =head2 EXAMPLE
  537.  
  538. This small example produces a 1 second sinusoidal
  539. wave at 440Hz and saves it in F<sinus.wav>:
  540.  
  541.     use Win32::Sound;
  542.     
  543.     # Create the object
  544.     $WAV = new Win32::Sound::WaveOut(44100, 8, 2);
  545.     
  546.     $data = ""; 
  547.     $counter = 0;
  548.     $increment = 440/44100;
  549.     
  550.     # Generate 44100 samples ( = 1 second)
  551.     for $i (1..44100) {
  552.  
  553.         # Calculate the pitch 
  554.         # (range 0..255 for 8 bits)
  555.         $v = sin($counter/2*3.14) * 128 + 128;    
  556.  
  557.         # "pack" it twice for left and right
  558.         $data .= pack("cc", $v, $v);
  559.  
  560.         $counter += $increment;
  561.     }
  562.     
  563.     $WAV->Load($data);       # get it
  564.     $WAV->Write();           # hear it
  565.     1 until $WAV->Status();  # wait for completion
  566.     $WAV->Save("sinus.wav"); # write to disk
  567.     $WAV->Unload();          # drop it
  568.  
  569. =head1 VERSION
  570.  
  571. Win32::Sound version 0.46, 25 Sep 1999.
  572.  
  573. =head1 AUTHOR
  574.  
  575. Aldo Calpini, C<dada@divinf.it>
  576.  
  577. Parts of the code provided and/or suggested by Dave Roth.
  578.  
  579. =cut
  580.  
  581.  
  582.