java播放mp3_java播放MP3的例子

这篇博客展示了如何使用Java来播放MP3文件。首先导入必要的包,然后通过AudioSystem获取AudioInputStream,并检查音频格式。如果需要,将音频格式转换为PCM_SIGNED。接着,获取SourceDataLine并打开它,读取音频文件内容并写入到数据线中,最后关闭数据线。
摘要由CSDN通过智能技术生成

1.导入播放mp3用的外部包

e051826976538ca48e39918a775869f0.png

2.编写代码

import java.io.File;

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;

public class PalyMusic {

public static void main(String[] args) {

AudioInputStream m_audioInputStream = null;

SourceDataLine m_line = null;

AudioFormat audioFormat = null;

try {

File file = new File("C:/Users/Administrator/Desktop/sss.mp3");

m_audioInputStream = AudioSystem.getAudioInputStream(file);

audioFormat = m_audioInputStream.getFormat();

if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)

{

AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioFormat.getSampleRate(), 16, audioFormat.getChannels(),audioFormat.getChannels() * 2, audioFormat.getSampleRate(),false);

System.out.println("开始转换音频格式:" + newFormat);

AudioInputStream newStream = AudioSystem.getAudioInputStream(newFormat, m_audioInputStream);

audioFormat = newFormat;

m_audioInputStream = newStream;

}

DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);

m_line = (SourceDataLine) AudioSystem.getLine(info);

m_line.open(audioFormat, m_line.getBufferSize());

m_line.start();

int bufferSize = (int) audioFormat.getSampleRate() * audioFormat.getFrameSize();

byte[] buffer = new byte[bufferSize];

int bytesRead = 0;

while (bytesRead >= 0) {

bytesRead = m_audioInputStream.read(buffer, 0, buffer.length);

if (bytesRead >= 0) {

m_line.write(buffer, 0, bytesRead);

}

}

m_line.drain();

m_line.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值