java sound api(JDK)原生支 .wav .au .aiff 这些格式的音频文件,当然 PCM(Pulse Code Modulation----脉冲编码调制)文件也是可以直接播放的,如果是 mp3,ogg,ape,flac 则需要第三方 jar 。
Stream.of(AudioSystem.getAudioFileTypes()).forEach(e -> {System.out.println(e.toString());});
音频格式 | 添加依赖 |
---|---|
*.wav *.au *.aiff | java sound api(JDK原生支持) |
*.mp3 *.mp4 *.ogg *.flac *.wav *.aif *.dsf *.wma (获取音频标签) | jaudiotagger.jar |
*.mp3 | mp3spi.jar |
*.mp3 | jl1.0.jar |
*.mp3 | jmp123.jar |
*.flac | jflac.jar |
方法1:使用官方开发的 JMF (Java Media Framework),现在JMF已经不再更新了。如果使用方法1,你必须安装好 JMF 软件并导入JMF安装目录下对应的jar包。
音频格式 | 添加依赖 |
---|---|
*.mp3 | jmf 安装目录的 jar 包 |
package com.xu.musicplayer.player;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
/**
* Java 播放音频
* @ClassName: MusicPlayer
* @Description: TODO
* @author: hyacinth
* @date: 2019年8月9日 上午12:10:53
* @Copyright: hyacinth
*/
public class MusicPlayer {
public static void main(String[] args) throws NoPlayerException, MalformedURLException, IOException {
File file = new File("F:\\KuGou\\张婉清、童英然、薛之谦、黄云龙 - 丑八怪.mp3");
Player player = Manager.createPlayer(file.toURL());
player.start();//开始播放
}
}
2 使用第三方jar包 jl1.0.jar。
音频格式 | 添加依赖 |
---|---|
*.mp3 | jl1.0.jar |
package com.xu.musicplayer.player;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
/**
* Java 播放音频
* @ClassName: MusicPlayer
* @Description: TODO
* @author: hyacinth
* @date: 2020年3月5日 上午12:10:53
* @Copyright: hyacinth
*/
public class MusicPlayer {
static Player player = null;
public static void main(String[] args) throws FileNotFoundException, JavaLayerException {
File file = new File("C:\\Users\\hyacinth\\Desktop\\Work\\花涵 - 假行僧.mp3");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream stream = new BufferedInputStream(fis);
Player player = new Player(stream);
player.play();
}
/**
* 播放 20 秒并结束播放
*/
public void play() {
new Thread(new Runnable() {
@Override
public void run() {
try {
File file = new File("C:\\Users\\hyacinth\\Desktop\\Work\\花涵 - 假行僧.mp3");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream stream = new BufferedInputStream(fis);
player = new Player(stream);
player.play();
} catch (Exception e) {
// TODO: handle exception
}
}
}).start();
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
player.close();
}
}
3 使用第三方jar包 jmp123.jar。
音频格式 | 添加依赖 |
---|---|
*.mp3 | jmp123.jar |
package com.xu.musicplayer.player;
import java.io.IOException;
import jmp123.PlayBack;
/**
* Java 播放音频
* @ClassName: MusicPlayer
* @Description: TODO
* @author: hyacinth
* @date: 2019年8月9日 上午12:10:53
* @Copyright: hyacinth
*/
public class MusicPlayer {
public static void main(String[] args) throws IOException {
PlayBack player = new PlayBack(new jmp123.output.Audio());
player.open("F:\\KuGou\\梦涵 - 爱的故事上集.mp3","");
player.start(true);
}
}
4 自定义通过获取MP3的PCM播放MP3,需要导入Google的一个jar包,可以获取音频的播放时长。
音频格式 | 添加依赖 |
---|---|
*.wav | 无 (JDK 原生支持) |
*.pcm | 无 (JDK 原生支持) |
*.au | 无 (JDK 原生支持) |
*.aiff | 无 (JDK 原生支持) |
*.mp3 | mp3spi.jar |
*.flac | jflac-codec.jar |
<dependency>
<groupId>com.googlecode.soundlibsgroupId>
<artifactId>mp3spiartifactId>
<version>1.9.5.4version>
dependency>
<dependency>
<groupId>org.jflacgroupId>
<artifactId>jflac-codecartifactId>
<version>1.5.2version>
dependency>
// float 类型 秒
AudioSystem.getAudioInputStream(new File("")).getFrameLength()/AudioSystem.getAudioInputStream(new File("")).getFormat().getSampleRate()
/**
* Java Music 获取音频文件信息
* @Title: get_info
* @Description: 获取音频文件信息
* @param path 音频文件路径
* @return 音频文件信息
* @date 2019年10月25日 下午12:28:41
*/
public String get_info(String path) {
File file=new File(path);
AudioInputStream ais;
String result="";
try {
ais = AudioSystem.getAudioInputStream(file);
AudioFormat af = ais.getFormat();
result = af.toString();
System.out.println(result);
System.out.println("音频总帧数:"+ais.getFrameLength());
System.out.println("每秒播放帧数:"+af.getSampleRate());
float len = ais.getFrameLength()/af.getSampleRate();
System.out.println("音频时长(秒):"+len);
System.out.println("音频时长:"+(int)len/60+"分"+(int)len%60+"秒");
} catch(UnsupportedAudioFileException e) {
throw new RuntimeException(e.getMessage());
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
package com.xu.music.player;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.id3.AbstractID3v2Frame;
import org.jaudiotagger.tag.id3.AbstractID3v2Tag;
import org.jaudiotagger.tag.id3.framebody.FrameBodyAPIC;
import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader;
/**
* Java 播放音频
* @ClassName: MusicPlayer
* @Description: TODO
* @author: hyacinth
* @date: 2019年10月25日 下午12:28:41
* @Copyright: hyacinth
*/
public class MusicPlayer {
public static void main(String[] args) throws Exception {
MusicPlayer player=new MusicPlayer();
//player.mp3_to_pcm("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.mp3", "C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.pcm");
//player.wav_to_pcm("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.wav", "C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.pcm");
player.get_info("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.pcm");
//player.get_info("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.wav");
//player.play_pcm("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.pcm");
//player.play_wav("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.wav");
player.play_mp3("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.mp3");
//player.play_flac("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.flac");
}
/**
* Java Music 播放 flac
* @Title: play_flac
* @Description: 播放 flac
* @param path flac文件路径
* @throws IOException
* @throws UnsupportedAudioFileException
* @date 2019年10月25日 下午12:28:41
*
*/
public void play_flac(String path) throws UnsupportedAudioFileException, IOException {
File file=new File(path);
if (!file.exists() || !path.toLowerCase().endsWith(".flac")) {
return;
}
AudioInputStream audio = AudioSystem.getAudioInputStream(file);
AudioFormat format = audio.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16, format.getChannels(), format.getChannels()*2, format.getSampleRate(), false);
audio = AudioSystem.getAudioInputStream(format, audio);
}
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format, AudioSystem.NOT_SPECIFIED);
SourceDataLine data = null;
try {
data = (SourceDataLine) AudioSystem.getLine(info);
data.open(format);
data.start();
byte[] bt = new byte[1024];
while (audio.read(bt) != -1) {
data.write(bt, 0, bt.length);
}
data.drain();
data.stop();
data.close();
audio.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Java Music 播放 wav
* @Title: play_wav
* @Description: 播放 wav
* @param path wav 文件路径
* @throws IOException
* @throws UnsupportedAudioFileException
* @date 2019年10月25日 下午12:28:41
*
*/
public void play_wav(String path) throws UnsupportedAudioFileException, IOException {
File file=new File(path);
if(!file.exists() || !path.toLowerCase().endsWith(".wav")) {
throw new RuntimeException("文件不存在");
}
AudioInputStream stream=AudioSystem.getAudioInputStream(file);
AudioFormat target = stream.getFormat();
DataLine.Info dinfo = new DataLine.Info(SourceDataLine.class, target);
SourceDataLine line = null;
int len = -1;
try {
line = (SourceDataLine) AudioSystem.getLine(dinfo);
line.open(target);
line.start();
byte[] buffer = new byte[1024];
while ((len = stream.read(buffer)) > 0) {
line.write(buffer, 0, len);
}
line.drain();
line.stop();
line.close();
stream.close();
}catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Java Music 播放 pcm
* @Title: play_pcm
* @Description: 播放 pcm
* @param path pcm文件路径
* @throws IOException
* @throws UnsupportedAudioFileException
* @date 2019年10月25日 下午12:28:41
*
*/
public void play_pcm(String path) throws UnsupportedAudioFileException, IOException {
File file=new File(path);
if(!file.exists() || !path.toLowerCase().endsWith(".pcm")) {
throw new RuntimeException("文件不存在");
}
AudioInputStream stream=AudioSystem.getAudioInputStream(file);
AudioFormat target = stream.getFormat();
DataLine.Info dinfo = new DataLine.Info(SourceDataLine.class, target, AudioSystem.NOT_SPECIFIED);
SourceDataLine line = null;
int len = -1;
try {
line = (SourceDataLine) AudioSystem.getLine(dinfo);
line.open(target);
line.start();
byte[] buffer = new byte[1024];
while ((len = stream.read(buffer)) > 0) {
line.write(buffer, 0, len);
}
line.drain();
line.stop();
line.close();
stream.close();
}catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Java Music 播放 mp3
* @Title: play_mp3
* @Description: 播放 mp3
* @param path mp3文件路径
* @throws IOException
* @throws UnsupportedAudioFileException
* @date 2019年10月25日 下午12:28:41
*
*/
public void play_mp3(String path) throws UnsupportedAudioFileException, IOException {
File file=new File(path);
if(!file.exists() || !path.toLowerCase().endsWith(".mp3")) {
throw new RuntimeException("文件不存在");
}
AudioInputStream stream = null;
//使用 mp3spi 解码 mp3 音频文件
MpegAudioFileReader mp = new MpegAudioFileReader();
stream = mp.getAudioInputStream(file);
AudioFormat baseFormat = stream.getFormat();
//设定输出格式为pcm格式的音频文件
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
// 输出到音频
stream = AudioSystem.getAudioInputStream(format, stream);
AudioFormat target = stream.getFormat();
DataLine.Info dinfo = new DataLine.Info(SourceDataLine.class, target, AudioSystem.NOT_SPECIFIED);
SourceDataLine line = null;
int len = -1;
try {
line = (SourceDataLine) AudioSystem.getLine(dinfo);
line.open(target);
line.start();
byte[] buffer = new byte[1024];
while ((len = stream.read(buffer)) > 0) {
line.write(buffer, 0, len);
}
line.drain();
line.stop();
line.close();
}catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
stream.close();
}
}
/**
* Java Music 读取pcm文件
* @Title: read_pcm
* @Description: 读取pcm文件
* @param path pcm文件路径
* @return AudioInputStream
* @date 2019年10月25日 下午12:28:41
*/
public AudioInputStream read_pcm(String path) throws UnsupportedAudioFileException, IOException {
File file=new File(path);
if(!file.exists()) {
return null;
}
AudioInputStream stream = AudioSystem.getAudioInputStream(file);
AudioFormat format=stream.getFormat();
System.out.println(format.toString());
return stream;
}
/**
* Java Music 获取 mp3 脉冲编码调制
* @Title: get_pcm_from_mp3
* @Description: 获取 mp3 脉冲编码调制
* @param rpath mp3文件路径
* @param spath pcm文件保存路径
* @return AudioInputStream
* @date 2019年10月25日 下午12:28:41
*/
public void get_pcm_from_mp3(String rpath,String spath) {
File file=new File(rpath);
if(!file.exists()) {
return;
}
AudioInputStream stream = null;
AudioFormat format = null;
try {
AudioInputStream in = null;
//读取音频文件的类
MpegAudioFileReader mp = new MpegAudioFileReader();
in = mp.getAudioInputStream(file);
AudioFormat baseFormat = in.getFormat();
//设定输出格式为pcm格式的音频文件
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
//输出到音频
stream = AudioSystem.getAudioInputStream(format, in);
AudioSystem.write(stream, AudioFileFormat.Type.WAVE, new File(spath));
stream.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Java Music mp3 转 pcm
* @Title: mp3_to_pcm
* @Description: MP3 PCM
* @param rpath MP3文件路径
* @param spath PCM文件保存路径
* @return AudioInputStream
* @date 2019年10月25日 下午12:28:41
*/
public void mp3_to_pcm(String rpath,String spath) {
File file=new File(rpath);
if(!file.exists()) {
return;
}
AudioInputStream stream = null;
AudioFormat format = null;
try {
AudioInputStream in = null;
//读取音频文件的类
MpegAudioFileReader mp = new MpegAudioFileReader();
in = mp.getAudioInputStream(file);
AudioFormat baseFormat = in.getFormat();
//设定输出格式为pcm格式的音频文件
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
//输出到音频
stream = AudioSystem.getAudioInputStream(format, in);
AudioSystem.write(stream, AudioFileFormat.Type.WAVE, new File(spath));
stream.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Java Music wav转pcm
* @Title: wav_to_pcm
* @Description: wav转pcm
* @param wpath wav文件路径
* @param ppath pcm文件保存路径
* @return AudioInputStream
* @throws IOException
* @throws UnsupportedAudioFileException
* @date 2019年10月25日 下午12:28:41
*/
public void wav_to_pcm(String wpath,String ppath) {
File file=new File(wpath);
if (!file.exists()) {
throw new RuntimeException("文件不存在");
}
AudioInputStream stream1;
try {
stream1 = AudioSystem.getAudioInputStream(file);
// 根据实际情况修改 AudioFormat.Encoding.PCM_SIGNED
AudioInputStream stream2=AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED,stream1);
AudioSystem.write(stream2,AudioFileFormat.Type.WAVE,new File(ppath));
stream2.close();
stream1.close();
} catch (UnsupportedAudioFileException | IOException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Java Music PCM转WAV
* @Title: pcm_to_wav
* @Description: PCM转WAV
* @param wpath WAV文件路径
* @param ppath PCM文件保存路径
* @return AudioInputStream
* @throws IOException
* @throws UnsupportedAudioFileException
* @date 2019年10月25日 下午12:28:41
*/
public void pcm_to_wav(String ppath,String wpath) {
}
/**
* Java Music 获取wav或者pcm文件的编码信息
* @Title: get_info
* @Description: 获取wav或者pcm文件的编码信息
* @param path wav或者pcm文件路径
* @return wav或者pcm文件的编码信息
* @date 2019年10月25日 下午12:28:41
*/
public String get_info(String path) {
File file=new File(path);
AudioInputStream ais;
String result="";
try {
ais = AudioSystem.getAudioInputStream(file);
AudioFormat af = ais.getFormat();
result = af.toString();
System.out.println(result);
System.out.println("音频总帧数:"+ais.getFrameLength());
System.out.println("每秒播放帧数:"+af.getSampleRate());
float len = ais.getFrameLength()/af.getSampleRate();
System.out.println("音频时长(秒):"+len);
System.out.println("音频时长:"+(int)len/60+"分"+len%60+"秒");
} catch(UnsupportedAudioFileException e) {
throw new RuntimeException(e.getMessage());
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
/**
* Java Music 获取mp3文件的图片
* @Title: get_image_from_mp3
* @Description: 获取mp3文件的图片
* @param mpath mp3flac文件路径
* @date 2019年10月25日 下午12:28:41
*
*/
public void get_image_from_mp3(String mpath) throws IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException {
File sourceFile = new File(mpath);
MP3File mp3file = new MP3File(sourceFile);
AbstractID3v2Tag tag = mp3file.getID3v2Tag();
AbstractID3v2Frame frame = (AbstractID3v2Frame) tag.getFrame("APIC");
FrameBodyAPIC body = (FrameBodyAPIC) frame.getBody();
byte[] image = body.getImageData();
Image img=Toolkit.getDefaultToolkit().createImage(image, 0,image.length);
ImageIcon icon = new ImageIcon(img);
FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.jpg");
fos.write(image);
fos.close();
System.out.println("width:"+icon.getIconWidth());
System.out.println("height:"+icon.getIconHeight());
}
}
5 使用 Google 的 mp3spi 播放MP3。添加 mp3spi 的 maven 依赖。
音频格式 | 添加依赖 |
---|---|
*.mp3 | mp3spi.jar |
<dependency>
<groupId>com.googlecode.soundlibsgroupId>
<artifactId>mp3spiartifactId>
<version>1.9.5.4version>
dependency>
/**
*
* @Author: hyacinth
* @Title: MusicPlayer.java
* @Package com.xu.test
* @Description: TODO:
* @Date: 2019年8月25日 下午10:40:47
* @Version V-1.0
* @Copyright: 2019 hyacinth
*
*/
package com.xu.test;
import java.io.File;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
/**
* @Author: hyacinth
* @ClassName: MusicPlayer
* @Description: TODO
* @Date: 2019年8月25日 下午10:40:47
* @Copyright: hyacinth
*/
public class MusicPlayer {
public static void main(String[] args) throws Exception {
File file=new File("I:\\KuGou\\许丽静 - 昨天今天下雨天.mp3");
FileInputStream stream=new FileInputStream(file);
Player player=new Player(stream);
player.play();
}
}
jaudiotagger.jar 本身不能播放 音频文件,但是能解码 音频文件 中的标签信息。
音频格式 | 添加依赖 |
---|---|
*.mp3 *.mp4 *.ogg *.flac *.wav *.aif *.dsf *.wma (获取音频标签) | jaudiotagger.jar |
<dependency>
<groupId>orggroupId>
<artifactId>jaudiotaggerartifactId>
<version>2.0.3version>
dependency>
package com.xu.music.player;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.TagException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class MusicPlayer {
public static void main(String[] args) throws Exception {
get_music_play_length("I:\\KuGou\\许丽静 - 昨天今天下雨天.mp3");
}
/**
* Java Music 获取歌曲播放时长
* @Title: get_music_play_length
* @Description: 获取歌曲播放时长
* @param path mp3路径
* @throws InvalidAudioFrameException
* @throws ReadOnlyFileException
* @throws TagException
* @throws IOException
* @throws CannotReadException
* @date 2019年10月25日 下午12:28:41
*/
public int get_music_play_length(String path) throws CannotReadException, IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException {
File file=new File("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.mp3");
AudioFile mp3=AudioFileIO.read(file);
return mp3.getAudioHeader().getTrackLength();
}
}
博主用 Java SWT 编写的 Java MusicPlayer
支持FFT频谱显示,默认不开启FFT频谱,喜欢的帮助点颗心。
Java MusicPlayer GitHub 地址