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

你可能感兴趣的:(thread,String,null,Class,import,byte)