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 播放
- jar 包:下载地址
- 代码:
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();
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于