java实现mp3功能_java实现MP3

下载MpegAudioSPI1.9.4

在项目中添加mp3spi1.9.4.jar  jl1.0.jar  tritonus_share.jar三个jar包

copy下面的代码到类中!

package org.mp3;

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 TestMP3 {

boolean isStop = true;// 控制播放线程

boolean hasStop = true;// 播放线程状态

AudioInputStream audioInputStream;// 音频文件流

AudioFormat audioFormat;// 文件格式

SourceDataLine sourceDataLine;// 输出设备

// 播放

private void play() {

try {

isStop = true;// 停止播放线程

// 等待播放线程停止

while (!hasStop) {

System.out.print(".");

try {

Thread.sleep(10);

} catch (Exception e) {

}

}

System.out.println("");

File file = new File("/home/mayi/11.mp3");//linux路径

// 取得文件输入流

audioInputStream = AudioSystem.getAudioInputStream(file);

audioFormat = audioInputStream.getFormat();

// 转换mp3文件编码

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

audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,

audioFormat.getSampleRate(), 16, audioFormat

.getChannels(), audioFormat.getChannels() * 2,

audioFormat.getSampleRate(), false);

audioInputStream = AudioSystem.getAudioInputStream(audioFormat,

audioInputStream);

}

// 打开输出设备

DataLine.Info dataLineInfo = new DataLine.Info(

SourceDataLine.class, audioFormat,

AudioSystem.NOT_SPECIFIED);

sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

sourceDataLine.open(audioFormat);

sourceDataLine.start();

// 创建独立线程进行播放

isStop = false;

Thread playThread = new Thread(new PlayThread());

playThread.start();

} catch (Exception e) {

e.printStackTrace();

}

}

//线程!!

class PlayThread extends Thread {

byte tempBuffer[] = new byte[320];

public void run() {

try {

int cnt;

hasStop = false;

// 读取数据到缓存数据

while ((cnt = audioInputStream.read(tempBuffer, 0,

tempBuffer.length)) != -1) {

if (isStop)

break;

if (cnt > 0) {

// 写入缓存数据

sourceDataLine.write(tempBuffer, 0, cnt);

}

}

// Block等待临时数据被输出为空

sourceDataLine.drain();

sourceDataLine.close();

hasStop = true;

} catch (Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

public static void main(String args[]) {

TestMP3 test=new TestMP3();

test.play();

}

}

运行!  OK    有空研究研究 audiospl的源码!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值