简体   繁体   中英

How to play .wav files in Java (looped)?

I've been rampaging about for a couple of hours now looking for sample code that can play simple wav files in Java. However, none of the ones I've received are working for me. Maybe it's just me that doesn't understand how to operate the sample code but could anyone provide me with sample code and "instructions" on how to get it working correctly. Any help would be much appreciated.

This code will create a clip and play it continuously once started:

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;


Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new URL(filename)));
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);

There are more modern ways to do this, but the applet class AudioClip might satisfy your needs:

import java.applet.Applet;
import java.applet.AudioClip;

final AudioClip clip = Applet.newAudioClip(resourceUrl);

To play it once:

clip.play();

To loop:

clip.loop();
clip.stop();

See Javadocs for Applet and AudioClip

getAudioClip

 public AudioClip getAudioClip(URL url) 

Returns the AudioClip object specified by the URL argument. This method always returns immediately, whether or not the audio clip exists. When this applet attempts to play the audio clip, the data will be loaded.

Parameters:

url - an absolute URL giving the location of the audio clip.

Returns:

the audio clip at the specified URL.

You don't need to actually be doing anything with applets for this to work. It will work fine in a regular Java application.

import java.io.File;
import javax.sound.sampled.*;

public void play(File file) 
{
    try
{
    final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));

        clip.addLineListener(new LineListener()
        {
        @Override
        public void update(LineEvent event)
            {
            if (event.getType() == LineEvent.Type.STOP)
                clip.close();
            }
        });

        clip.open(AudioSystem.getAudioInputStream(file));
        clip.start();
    }
        catch (Exception exc)
    {
        exc.printStackTrace(System.out);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM