`
superlxw1234
  • 浏览: 542744 次
  • 性别: Icon_minigender_1
  • 来自: 西安
博客专栏
Bd1c0a0c-379a-31a8-a3b1-e6401e2f1523
Hive入门
浏览量:43291
社区版块
存档分类
最新评论

java播放mp3(不用jmf)

    博客分类:
  • java
阅读更多

帮一个小妹写一个播放mp3的代码,对于java不熟的我来说可真折腾。

 

网上好多代码都是用jmf的,需要单独安装,除了jar包,还依赖很多dll文件。

 

找了又找,终于找到一个只依赖jar包的;

 

原帖地址:http://blog.csdn.net/liuzhongbing/article/details/4535402

 

依赖的jar包见附件。

 

import java.io.File;
import java.io.IOException;

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 Test {
	public static void main(String[] args) throws Exception, IOException {
		AudioInputStream audioInputStream;// 文件流
		AudioFormat audioFormat;// 文件格式
		SourceDataLine sourceDataLine;// 输出设备
		File file = new File("E:/5.mp3");

		// 取得文件输入流
		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();
		
		byte tempBuffer[] = new byte[320];
		try {
			int cnt;
			// 读取数据到缓存数据
			while ((cnt = audioInputStream.read(tempBuffer, 0,
					tempBuffer.length)) != -1) {
				if (cnt > 0) {
					// 写入缓存数据
					sourceDataLine.write(tempBuffer, 0, cnt);
				}
			}
			// Block等待临时数据被输出为空
			sourceDataLine.drain();
			sourceDataLine.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
	}
}
 
0
1
分享到:
评论
3 楼 ming1332236 2014-04-11  
感谢楼主 这个真的可以使用!
2 楼 goodscx 2013-10-15  
真心不错,特别好用,感谢楼主!
1 楼 BlackGray 2012-06-26  
原帖还没看,本帖报:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file

查过,格式不支持:
http://www.guan8.net/Java/102673.html

相关推荐

Global site tag (gtag.js) - Google Analytics