HOWTO: Playing a .WAV file in Java

ID: Q179850


The information in this article applies to:


SUMMARY

The Applet and AudioClip class only play .AU files. Microsoft offers two solutions to play .WAV files when using the Microsoft virtual machine.

The Microsoft SDK for Java 2.0 and later includes a sample, DirectX3\dSound, demonstrating how to use DirectSound to play .WAV files from a URL. It is also possible to use the Winmm class to play a .WAV file from the local drive, although your program must be trusted.


MORE INFORMATION

The sample code below demonstrates how to use the Winmm class to play a .WAV file. This sample requires you place a .WAV file in the current directory and name the file "sound.wav".

Sample Code


import com.ms.win32.Winmm;
import com.ms.win32.wins;

public class PlayWav {
  public static void main(String args[])
  {
    WavAudio ac = new WavAudio("sound.wav");
    System.out.println("Looping sound...");
    ac.loop();
    try {
      Thread.sleep(20000);
    } catch (Exception e) {
    }
    System.out.println("stoping audio.");
    ac.stop();
  }
}

class WavAudio {
  String wavFile=null;
  public WavAudio(String file) {
    wavFile=file;
  }
  public void stop() {
    Winmm.PlaySound(null,0,
       wins.SND_ASYNC|wins.SND_FILENAME|wins.SND_NOWAIT);
  }
  public void play() {
    stop();
    Winmm.PlaySound(wavFile,0,
      wins.SND_ASYNC|wins.SND_FILENAME|wins.SND_NOWAIT);
  }
  public void loop() {
    Winmm.PlaySound(wavFile,0,
      wins.SND_ASYNC|wins.SND_LOOP|wins.SND_FILENAME|wins.SND_NOWAIT);
  }
} 


REFERENCES

For more information please see the Microsoft SDK for Java documentation, available at http://www.microsoft.com/java/sdk.

For additional information, please see the following article in the Microsoft Knowledge Base:

Q178707 Unable to play .Wav file from Applet or Audio Clip

Additional query words: audio .wav winmm


Keywords          : kbSDKJava300 kbSDKJava310 AWTPkg kbSDKJava320 
Version           : WINDOWS:2.0,2.01,2.02,3.0,3.1
Platform          : WINDOWS 
Issue type        : kbhowto 

Last Reviewed: July 26, 1999