⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 audioplayer.java

📁 一个java版的简易音频播放器
💻 JAVA
字号:
package com.mars.auplayer;


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.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AudioPlayer implements Runnable{

	AudioInputStream auIS;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成方法存根
		AudioPlayer audioPlayer=new AudioPlayer();
		Thread playerThread=new Thread(audioPlayer);
		playerThread.start();
		
		try{
			Thread.sleep(2000);
		}
		catch(InterruptedException ex){
			System.out.println(ex.getMessage());
		}
	}
	
	public void playAudio(){
		
		AudioFormat audioFormat=null;
//		AudioFormat baseFormat=null;
		SourceDataLine dataLine=null;
//		通过AudioSystem获取AudioInputStream
		try{
			auIS=AudioSystem.getAudioInputStream(new File("alarm.wav"));
			if(auIS!=null){
				audioFormat=auIS.getFormat();
				/*
				非WAV,AIFF和UA格式的音频文件播放方法
				System.out.println(baseFormat.getFrameRate());
				System.out.println(baseFormat.getChannels());
				System.out.println(baseFormat.getFrameSize());
				System.out.println(baseFormat.getSampleRate());
				System.out.println(baseFormat.getSampleSizeInBits());
				audioFormat=new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,baseFormat.getSampleRate(),16,
				baseFormat.getChannels(),
				baseFormat.getChannels()*2,
				baseFormat.getSampleRate(),
				false
				);*/
				dataLine=getLine(audioFormat);
				play(auIS,dataLine);
			}
		}
		catch(IOException ex){
			System.out.println("打开音频文件出错!"+ex.getMessage());
		}
		catch(UnsupportedAudioFileException ex){
			System.out.println("音频文件格式不支持"+ex.getMessage());
		}
	}
	
	public void run(){
		playAudio();
	}
	
	private SourceDataLine getLine(AudioFormat audioFormat){
		SourceDataLine srcDataLine=null;
		DataLine.Info info=new DataLine.Info(SourceDataLine.class,audioFormat);
		
		try{
			srcDataLine=(SourceDataLine)AudioSystem.getLine(info);
			srcDataLine.open(audioFormat);
		}
		catch(LineUnavailableException ex){
			System.out.println("DataLine 不可用!"+ex.getMessage());
		}
		return srcDataLine;
	}
	
	private void play(AudioInputStream auIS,SourceDataLine srcDataLine){
		int inLen=0;
		int outLen=0;
		final int BUFFER_SIZE=1024;
		byte[] audioData=new byte[BUFFER_SIZE];
		
		while(inLen!=-1){
			try{
				inLen=auIS.read(audioData,0,BUFFER_SIZE);
				System.out.println(inLen);
			}
			catch(IOException ex){
				System.out.println("读取音频数据出错!"+ex.getMessage());
			}
			if(inLen>=0){
				outLen=srcDataLine.write(audioData, 0, inLen);
				srcDataLine.start();
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -