for循环用于避免一次播放音频文件

时间:2015-03-16 17:39:21

标签: java loops for-loop

 public static void Audio2(String filename) {
    // String filename = "chaithurest";
    if (filename.equals("test1")) { 
        String test1= System.getProperty("user.dir")+"//test1.wav";
        filename = test1;
    }
    else if (filename.equals("test2")) { 
        String test2=System.getProperty("user.dir")+"//test2.wav";
        filename = test2;
    }
    else
        filename  = filename;
    try {
        InputStream in = new FileInputStream(new File(filename ));
        AudioStream audioStream = new AudioStream(in);
        AudioPlayer.player.start(audioStream);
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}

此代码仅在我传递一个文件名时才有效。如果我通过调用此程序传递多个文件名,则两个音频文件同时播放。我有可能一个接一个地玩。

我将此audio2文件称为

if (!ARRAY.contains(filename)) {    
    Audio2(filename);
}

2 个答案:

答案 0 :(得分:0)

sun.audio.AudioPlayer提供stop(InputStream)方法。为了防止播放多个文件,您可以在Audio2()中添加一些逻辑,例如:

在课程中添加audioStream成员,并在游戏时进行设置:

 // In the class
 static AudioStream currentAudioStream = null;

 public static void Audio2(String filename) {
    //...
    try {
        if (currentAudioStream != null) {
           AudioPlayer.player.stop(audioStream);
        }
        InputStream in = new FileInputStream(new File(filename ));
        currentAudioStream = new AudioStream(in); // <= set member
        AudioPlayer.player.start(audioStream);
    }
    //...
 }

答案 1 :(得分:0)

public static void Audio2(String filename) {
// String filename = "chaithurest";
if (filename.equals("test1")) { 
    String test1= System.getProperty("user.dir")+"//test1.wav";
    filename = test1;
}
else if (filename.equals("test2")) { 
    String test2=System.getProperty("user.dir")+"//test2.wav";
    filename = test2;
}
else
    filename  = filename;
try {
    InputStream in = new FileInputStream(new File(filename ));
    AudioStream audioStream = new AudioStream(in);
    AudioPlayer.player.start(audioStream);
     AudioPlayer.player.join(6000);
}
catch (Exception e) {
    throw new RuntimeException(e);
}
}