home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _f72685af02e33ea72fcd09a05e206b22 < prev    next >
Text File  |  2000-03-15  |  15KB  |  581 lines

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