播放声音的类
复制代码代码如下:
导入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);
}
}
}