我怎样才能让我的程序循环播放wav文件列表?

时间:2019-04-03 23:07:43

标签: java audio wav

我终于在我制作的游戏中加入了配乐,但只有一首歌。我如何才能在一些歌曲中循环播放这些歌曲以扩展音轨?

 try{
        AudioInputStream stream;
        AudioFormat format;
        DataLine.Info info;
        Clip clip;

        stream = AudioSystem.getAudioInputStream(new File("Spring.wav"));

        format = stream.getFormat();
        info = new DataLine.Info(Clip.class, format);
        clip = (Clip) AudioSystem.getLine(info);
        clip.open(stream);
                  //plays the song
        clip.start();

                  //keeps the song on repeat
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    }
    catch (Exception e) {

    }

1 个答案:

答案 0 :(得分:0)

您的代码实际上不会播放任何声音,因为线程会立即关闭。在我的示例中,我添加了thread.sleep命令。下一个问题:删除clip.loop行,因为您不希望那样做。    在我的版本中,这个想法是将玩家分成自己的班级,该班级将从主队开始比赛。这样,您可以使播放器的实例一次播放一个音调,然后以您希望的任何方式切换它。在该示例中,我选择一个接一个地播放每个wave文件,但是如果愿意,您可以随机播放或播放整个wave文件:

班级:

package scrapAudioClips;

import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;

public class AudioPlayer {

public void play(String filename) {
//The filename and time to play are passed into the method.
    try {
        AudioInputStream stream1;
        AudioFormat format = null;
        DataLine.Info info;
        Clip clip;


        stream1 = AudioSystem.getAudioInputStream(new File(filename));


        format = stream1.getFormat();

        info = new DataLine.Info(Clip.class, format);
        clip = (Clip) AudioSystem.getLine(info);
        clip.open(stream1);

//These next two lines will get the length of the wave file for you...
        long frames = stream1.getFrameLength();
        double durationInSeconds = (frames+0.0) / format.getFrameRate();

        // plays the song
        clip.start();

        // clip.loop(Clip.LOOP_CONTINUOUSLY); You don't need this anymore.

        Thread.sleep((long)(durationInSeconds * 1000)); // This allows you to actually hear the audio for the time in seconds..

    } catch (Exception e) {
        System.out.println("File not recognized");
    }
}

}

主要:

package scrapAudioClips;

public class scrapAudio {

public static void main(String[] args) {

    AudioPlayer player = new AudioPlayer();

    //you may play sequentially or in any random order you want with any loop     structure you like...
    player.play("Alesis.wav"); //You just pass the file name in... 
    player.play("wavefile1.wav");//Make your own playlist class as an array...
    player.play("wavefile2.wav");//loop it randomly or in sequence...

}

}