今天把AudioPlay类的代码放出来
public class AudioPlay {
private URL radio = null;
private AudioClip clip = null;
private File file = null;
public AudioPlay(String path) throws MalformedURLException {
file = new File(path);
radio = file.toURL();
clip = Applet.newAudioClip(radio);
}
public void play(){
clip.play();
}
}
AudioPlay类在产生新对象的时候把要播放的文件的路径传参进来,然后调用play方法的时候就能播放相应音频。
只是这里有个小问题我不太明白,恳请各位java大神解答。
我在这个AudioPlay类里所使用的这些个类和方法都已经被标记为deprecated
public class App {
private AudioFormat audioFormat = null;
private SourceDataLine sourceDataLine = null;
private DataLine.Info dataLine_info = null;
// private String file = "D:/workspace_mars/wav/src/main/resources/music/12.wav";
private String file="http://test.kuanrf.com:81/gs/audio/2016/09/23/3f9eef64b9284e25b32bc2df80a0049e.wav";
private AudioInputStream audioInputStream = null;
public App() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
//audioInputStream = AudioSystem.getAudioInputStream(new File(file));
audioInputStream=AudioSystem.getAudioInputStream(new URL(file));
audioFormat = audioInputStream.getFormat();
System.out.println("每秒播放帧数:"+audioFormat.getSampleRate());
System.out.println("总帧数:"+audioInputStream.getFrameLength());
System.out.println("音频时长(秒):"+audioInputStream.getFrameLength()/audioFormat.getSampleRate());
dataLine_info = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLine_info);
}
public void play() throws IOException, LineUnavailableException {
byte[] b = new byte[1024];
int len = 0;
sourceDataLine.open(audioFormat, 1024);
sourceDataLine.start();
while ((len = audioInputStream.read(b)) > 0) {
sourceDataLine.write(b, 0, len);
}
audioInputStream.close();
sourceDataLine.drain();
sourceDataLine.close();
}
public static void main(String[] args) {
try {
new App().play();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
}
但是当我使用如上方式实现音频播放运行游戏的时候就会特别卡(如上代码是我从网上复制的,侵删),使用被标为deprecated的方法和类时就没有这个问题,请问各位大神是为什么?有什么解决办法吗?(java初学者,见笑了)