更好的重置java AudioStream的方法

时间:2016-05-22 19:24:36

标签: java audio loading

截至目前,我正在使用AudioPlayer为我的游戏创建声音效果,我很难找到一种简单的方法来重置音频,然后再开始播放。截至目前,我只是完全重新加载AudioStream,继承我的代码,欢迎任何建议。

package resources;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;

import javax.sound.sampled.Clip;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class Audio {

    private static HashMap<String, AudioStream> sounds = new HashMap<String, AudioStream>();
    private static HashMap<String, Long> times = new HashMap<String, Long>();

    Clip c;

    public static AudioStream getAudio(String s){
        if(sounds.containsKey(s))
            return sounds.get(s);
        return null;
    }

    public static void loadAllAudio(){
        File f = new File("res/sounds");
        String[] files = f.list();
        for(String s:files){
            if(s.endsWith(".wav")){
                loadAudio(s);
                System.out.println("Loaded Audio: "+s);
            }
        }
    }

    public static double getSoundLength(String sound){
        return getAudio(sound).getLength()/192000.0;
    }

    public static void playSound(String name){
        resetSound(name);
        times.put(name, System.nanoTime());
        AudioPlayer.player.start(sounds.get(name));
    }

    public static void resetSound(String name){
        loadAudio(name);
    }

    public static void stopSound(String sound){
        AudioPlayer.player.stop(sounds.get(sound));
        times.put(sound, System.nanoTime());
    }

    private static void loadAudio(String name){
        try {
            File f = new File("res/sounds/"+name);
            sounds.put(name, new AudioStream(new FileInputStream(f)));
            times.put(name, 0L);
        } catch (Exception e) {}
    }

    public static double getTime(String sound) {
        long time = times.get(sound);
        if(time==0)
            return 0;
        return (System.nanoTime()-time)/1E9;
    }
}

我想替换的行是:

public static void playSound(String name){
    ---------resetSound(name);--------- THIS LINE
    times.put(name, System.nanoTime());
    AudioPlayer.player.start(sounds.get(name));
}

1 个答案:

答案 0 :(得分:0)

您可以使用支持 .mp3

JLayer

如何使用 JLayer 播放声音的示例:

new Thread(()->{
   try {
        FileInputStream file = new FileInputStream("path ..../audio.mp3"); //initialize the FileInputStream
        Player player= new Player(file); //initialize the player
        player.play(); //start the player
    } catch (Exception e) {
       e.printStackTrace();
    }

 }).start();

注意:

请注意,如果不是应用程序堆叠,我将使用单独的线程原因。