Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

582 lines
14 KiB

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