2 回答
TA贡献1794条经验 获得超8个赞
为音频添加导入,
import java.io.*;
import sun.audio.*;
public class PlayMySoundApplication
{
public static void main(String[] args)
throws Exception
{
// open the sound file as a Java input stream
String applause2x = "/Users/pc/Desktop/applause2x.wav";
InputStream in = new FileInputStream(applause2x);
// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);
}
}
TA贡献2021条经验 获得超8个赞
我不知道您要使用什么声音库。
如果您使用的是不错的 JDK 版本,那应该可以解决问题:
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 MakeSound {
public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
playSound("test.wav");
}
public static void playSound(String strFilename)
throws LineUnavailableException, UnsupportedAudioFileException, IOException {
File soundFile = new File(strFilename);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundFile);
AudioFormat audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try (SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(info);) {
sourceLine.open(audioFormat);
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[128000];
while (nBytesRead != -1) {
nBytesRead = audioStream.read(abData, 0, abData.length);
if (nBytesRead > 0) {
sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
}
}
}
!
添加回答
举报