一个播放音频文件的小程序,播放时显示wave form(波形),文件信息(名称,解码,声道,bits,大小)。
暂时只支持.wav文件。
Written by Chengliang_Dong, University of Wollongong. 2006
运行环境: Windows, Mac OS
程序下载: JukeBox
部分代码说明:
LoadMusic method 用于读取指定的wave file并且读取wave file的信息
private void LoadMusic(File f)
{
//Init Line to null
line = null;
try
{
//Get audio inputstream
au = AudioSystem.getAudioInputStream(f);
}catch(Exception ex)
{
ex.printStackTrace();
}
//get audio format information
aufm = au.getFormat();
String c;
//if Channels is one the audio is mono otherwise is stereo
if (aufm.getChannels() == 1)
{
c = "mono";
}
else
{
c = "stereo";
}
//read audio information
Infor = f.getName() + " Encoding:" + aufm.getEncoding() + " SampleRate:" + aufm.getSampleRate() + " " + c
+ " " + aufm.getSampleSizeInBits() + "bits "
+ Math.round(au.getFrameLength()/aufm.getFrameRate()) + "seconds"; //Calculate audio second then round to seconds
//dataline
DataLine.Info lineInfor = new DataLine.Info(SourceDataLine.class,aufm);
try
{
//assign to line.
line = (SourceDataLine) AudioSystem.getLine(lineInfor);
}catch(LineUnavailableException ex)
{
ex.printStackTrace();
}
}
Thread Class AudioT, 用于读取声音缓存,并写如line进行播放。 注意:必须使用thread,以避免读取文件循环过程中程序占用所有资源
//Thread Class to avoid program using all the resources
class AudioT extends Thread{
//init nBytesRead to store how many data will read
int nBytesRead =1;
//create a buffData array to store the audio information
byte buffData []= new byte[buffSize];
public void run(){
try{
//if nBytesRead not equa -1, which means there is an audio file waiting to play
while (nBytesRead!=-1)
{
//if play flag is true
if (play_flag == true)
{
//check if the line lis running, if not, open the line and start it
if (!line.isRunning())
{
line.open(aufm);
line.start();
}
try{
//read the 256 bytes information
nBytesRead = au.read(buffData,0,buffData.length);
}catch(IOException e){
e.printStackTrace();
}
if (nBytesRead >=0){
//write to line, so the program will play the information (music)
int nBytesWritten = line.write(buffData,0,nBytesRead);
//getData method, to generate a 128 bytes audio waveform information
short[] xPoints = getData(buffData,aufm.getChannels());
//pass the data to Canvas Panel to display the waveform
cv.getData(xPoints);
}
}
} //end of while loop, which means that the file is ended
//clear the buffer and send the empty information to Canvas so it display a line
short[] xPoints;
xPoints = new short[128];
for (int i = 0; i < xPoints.length; i++)
{
xPoints[i] = 0;
}
cv.getData(xPoints);
//stop and close the line
line.drain();
line.stop();
line.close();
line = null;
play_flag = false;
//if the repeat tag is true. reopen the file and play it
if (repeat)
{
PlayAudio();
}
}catch(Exception e){
}
}
}