播放聲音的類
複製程式碼如下:
導入java.io.File;
導入java.io.IOException;
導入 javax.sound.sampled.AudioFormat;
導入 javax.sound.sampled.AudioInputStream;
導入 javax.sound.sampled.AudioSystem;
導入 javax.sound.sampled.DataLine;
導入 javax.sound.sampled.SourceDataLine;
//播放聲音的類別
公共類別 PlaySounds 擴充線程 {
私有字串檔名;
公共 PlaySounds(字串 wavfile){
檔案名稱 = System.getProperty("user.dir")+wavfile;
}
公共無效運行(){
檔案 soundFile = new File(檔案名稱);
音頻輸入流 音頻輸入流 = null;
嘗試 {
音訊輸入流 = AudioSystem.getAudioInputStream(soundFile);
} catch (異常 e1) {
e1.printStackTrace();
返回;
}
AudioFormat 格式 = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
嘗試 {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(格式);
} catch (異常 e) {
e.printStackTrace();
返回;
}
auline.start();
int nBytesRead = 0;
//這是緩衝
位元組[] abData = 新位元組[512];
嘗試 {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
返回;
} 最後 {
auline.drain();
auline.close();
}
}
}
下面是一個java播放聲音的應用程序,可以單次播放聲音、循環播放聲音
MusicPaly myMusicPlay = new MusicPlay(getClass().getResource("/music/button.wav"));
myMusicPlay.start();//播放一次
myMusicPlay .stop();//停止
myMusicPlay .continuousStart();//循環播放
myMusicPlay .continuousStop();//停止
複製程式碼如下:
// 檔名:MuiscPlay.java
導入java.io.*;
導入java.net.URL;
導入sun.audio.*;
/**
*
* @作者吳慧文
* 播放音訊文件,產生音效
*/
公共課音樂播放{
私有音訊流為; //單次播放聲音用
ContinuousAudioDataStream cas;//循環播放聲音
//建構函式
公共音樂播放(URL url)
{
嘗試 {
//開啟一個聲音檔案流作為輸入
as = new AudioStream(url.openStream());
} catch (FileNotFoundException e) {
// TODO 自動產生的 catch 區塊
e.printStackTrace();
} catch (IOException e) {
// TODO 自動產生的 catch 區塊
e.printStackTrace();
}
}
// 一次播放開始
公共無效開始()
{
如果(as==null){
System.out.println("AudioStream物件沒有創建!");
返回;
}別的{
AudioPlayer.player.start(as);
}
}
// 一次播放停止
公共無效停止()
{
如果(as==null){
System.out.println("AudioStream物件沒有創建!");
返回;
}別的{
AudioPlayer.player.stop(as);
}
}
// 循環播放開始
公共無效連續開始()
{
// 建立音訊資料來源。
音訊資料資料=空;
嘗試 {
資料 = as.getData();
} catch (IOException e) {
// TODO 自動產生的 catch 區塊
e.printStackTrace();
}
// 建立連續音訊資料流。
cas = new ContinuousAudioDataStream (資料);
// 播放音訊。
AudioPlayer.player.start(cas);
}
// 循環播放停止
公共無效連續停止()
{
if(cas!= null)
{
AudioPlayer.player.stop(cas);
}
}
}