java音频播放器备份,支持wav,mp3
播放wav版本
包:
不需要其他jar包
代码:
package com;
import javax.sound.sampled.*;
import java.io.File;
/*
wav播放器,不支持mp3
*/
public class AePlayWave extends Thread {
private String name;
public AePlayWave(String name) {
this.name = name;
}
@Override
public void run() {
File file = new File(name);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(file);
} catch (Exception e) {
e.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (Exception e) {
e.printStackTrace();
return;
}
auline.start();
int nBytesRead = 0;
byte[] abbytes = new byte[512];
try {
while ((nBytesRead = audioInputStream.read(abbytes, 0, abbytes.length)) != -1) {
if (nBytesRead >= 0) {
auline.write(abbytes, 0, nBytesRead);
}
}
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
MP3播放
代码:
package com;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/*
mp3播放器
*/
public class AudioPlayer extends Thread {
Player player;
File music;
//构造方法
public AudioPlayer(String fileName) {
this.music = new File(fileName);
}
//重写run方法
@Override
public void run() {
super.run();
try {
play();
} catch (FileNotFoundException | JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//播放方法
public void play() throws FileNotFoundException, JavaLayerException {
BufferedInputStream buffer =
new BufferedInputStream(new FileInputStream(music));
player = new Player(buffer);
player.play();
}
}