java中如何播放wav,如何播放.wav用java文件

I am trying to play a *.wav file with Java. I want it to do the following:

When a button is pressed, play a short beep sound.

I have googled it, but most of the code wasn't working. Can someone give me a simple code snippet to play a .wav file?

解决方案

Finally I managed to do the following and it works fine

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;

public class MakeSound {

private final int BUFFER_SIZE = 128000;

private File soundFile;

private AudioInputStream audioStream;

private AudioFormat audioFormat;

private SourceDataLine sourceLine;

/**

* @param filename the name of the file that is going to be played

*/

public void playSound(String filename){

String strFilename = filename;

try {

soundFile = new File(strFilename);

} catch (Exception e) {

e.printStackTrace();

System.exit(1);

}

try {

audioStream = AudioSystem.getAudioInputStream(soundFile);

} catch (Exception e){

e.printStackTrace();

System.exit(1);

}

audioFormat = audioStream.getFormat();

DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);

try {

sourceLine = (SourceDataLine) AudioSystem.getLine(info);

sourceLine.open(audioFormat);

} catch (LineUnavailableException e) {

e.printStackTrace();

System.exit(1);

} catch (Exception e) {

e.printStackTrace();

System.exit(1);

}

sourceLine.start();

int nBytesRead = 0;

byte[] abData = new byte[BUFFER_SIZE];

while (nBytesRead != -1) {

try {

nBytesRead = audioStream.read(abData, 0, abData.length);

} catch (IOException e) {

e.printStackTrace();

}

if (nBytesRead >= 0) {

@SuppressWarnings("unused")

int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);

}

}

sourceLine.drain();

sourceLine.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值