简体   繁体   English

如何在Java中播放.wav文件(循环播放)?

[英]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. 我已经忙了大约两个小时,现在正在寻找可以在Java中播放简单wav文件的示例代码。 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: 有更现代的方法可以执行此操作,但是applet类AudioClip可能满足您的需求:

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 请参阅Javadocs中的AppletAudioClip

getAudioClip getAudioClip

 public AudioClip getAudioClip(URL url) 

Returns the AudioClip object specified by the URL argument. 返回URL参数指定的AudioClip对象。 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. url-提供音频剪辑位置的绝对URL。

Returns: 返回:

the audio clip at the specified URL. 指定URL上的音频剪辑。

You don't need to actually be doing anything with applets for this to work. 您实际上不需要对applet进行任何操作即可使它起作用。 It will work fine in a regular Java application. 它将在常规Java应用程序中正常工作。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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