javaSE播放声音实例

源码:

import javax.sound.sampled.*;
import java.io.*;
public class AudioTest implements Runnable{
	
	private AudioInputStream ais=null;
	private AudioFormat format=null;
	private Line.Info info=null;
	private SourceDataLine sourceData=null;
	
	
	public AudioTest(String str){
		try {
			ais=AudioSystem.getAudioInputStream(new File(str));//得到了输入流
			format=ais.getFormat();//得到了格式
			info=new Line.Info(SourceDataLine.class);
			sourceData=(SourceDataLine)AudioSystem.getLine(info);
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}
	//开始播放
	public void play(){
		try {
			sourceData.open(format);
			sourceData.start();
			byte b[]=new byte[1024];//1k
			int readCount=0;
			while((readCount=ais.read(b))!=-1){
				sourceData.write(b, 0, readCount);
			}
			Thread.sleep(500);
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			try {				
				if(sourceData!=null){
					sourceData.drain();
					sourceData.close();
				}
				if(ais!=null){				
					ais.close();				
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void run(){
		play();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AudioTest at=new AudioTest("./images/start.wav");
		Thread t=new Thread(at);
		t.start();
	}
}

刚学的音频播放实例,暂时只支持wav格式的音频,如需对MP3支持,需下载相关的jar,具体请参见: http://www.yesky.com/SoftChannel/72342371961929728/20030618/1708754.shtml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值