java wav播放,用Java播放.wav歌曲?

I'm trying to play a song in the .wav format in my Java Game, and here's some of the code of the SoundPlayer class:

private static HashMap clips;

private static int gap;

public static void init() {

clips = new HashMap();

gap = 0;

}

public static void load(String s, String n) {

if(clips.get(n) != null) return;

Clip clip;

try {

InputStream in = SoundPlayer.class.getResourceAsStream(s);

InputStream bin = new BufferedInputStream(in);

AudioInputStream ais = AudioSystem.getAudioInputStream(bin);

AudioFormat baseFormat = ais.getFormat();

AudioFormat decodeFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);

AudioInputStream dais = AudioSystem.getAudioInputStream(decodeFormat, ais);

clip = AudioSystem.getClip();

clip.open(dais);

clips.put(n, clip);

} catch(Exception e) {

e.printStackTrace();

}

}

When I call the load() method, it crashes on the line clip.open(dais) and I'm given this error:

javax.sound.sampled.LineUnavailableException: Failed to allocate clip data: Requested buffer too large.

This works with short sound effects, so I'm guessing this is because the file is over a minute long. Are there any better ways of doing this?

Thanks!

解决方案

I've had some trouble in the past getting sound to work in Java. Here is a good way to load .wav soundclips.

private Clip clip;

public Sound(String fileName)

{

try

{

File file = new File(fileName);

if (file.exists())

{

AudioInputStream sound = AudioSystem.getAudioInputStream(file);

clip = AudioSystem.getClip();

clip.open(sound);

}

else

{

throw new RuntimeException("Sound: file not found: " + fileName);

}

}

catch (UnsupportedAudioFileException e)

{

e.printStackTrace();

throw new RuntimeException("Sound: Unsupported Audio File: " + e);

}

catch (IOException e)

{

e.printStackTrace();

throw new RuntimeException("Sound: Input/Output Error: " + e);

}

}

public void play()

{

clip.setFramePosition(0);

clip.start();

}

public void loop()

{

clip.loop(Clip.LOOP_CONTINUOUSLY);

}

public void stop()

{

clip.stop();

}

I find that this works great! You can add more exceptions if you'd like as well, like LineUnavailableException, and MalformedURLException. To create a sound clip you make something as such:

private Sound sound = new Sound("/sounds/sound.wav");

then doing

sound.play();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值