如何在 Java 游戏中播放声音? [英] How to play sounds in Java games?

查看:38
本文介绍了如何在 Java 游戏中播放声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码在 Java (1.5) 小程序游戏中成功播放声音:

I'm successfully playing sounds in a Java (1.5) applet game using the following code:

// get an available clip to play it
Clip clip = null;
for (Clip clipTemp : players) {
    if (!clipTemp.isOpen()) {
    clip = clipTemp;
        break;
    }
}
if (clip == null) {
    // no available player found, don't play
    return;
}

clip.open(audioFormat, audioByteData, 0, audioByteData.length);

clip.start();

(播放器是我在开始时打开的剪辑列表,目的是减少延迟,当检索到停止事件时,线路侦听器会关闭线路.)

(Players are a list of clips that I open at the start with the aim to reduce latency, a line listener closes the line when the stop event is retrieved.)

我面临的问题是播放声音时最多 1 秒的间歇性延迟.这很可怜.

The problem I'm facing is intermittent delays of upto 1 second when playing a sound. This is pretty poor.

有什么办法可以改善吗?SourceDataLines 值得考虑吗?

Is there any way to improve this? Are SourceDataLines worth considering?

推荐答案

Java Applet 会在您想要播放剪辑时对其进行流式传输,这就是为什么您会因为声音文件尚未加载到内存而出现延迟的原因

The Java Applet is streaming your clip whenever you want to play it, which is why you are getting a delay as the sound file hasn't been loaded into memory yet.

我已经有一段时间没有进行 Java 小程序编程了,但我确实记得我曾经预先加载我的所有剪辑,然后随后调用播放不会重新打开文件.

It's been awhile since I have done Java applet programming, but I do remember that I used to pre-load all my clips and then subsequent calls to play would not re-open the files.

这是我的一个旧项目中的一些代码

Here is some code from one of my old projects

Clip shoot;

private loadShootWav()
{
    AudioInputStream sample;
    sample = AudioSystem.getAudioInputStream(this.getClass().getResource("shoot.wav"));
    shoot = AudioSystem.getClip();
    shoot.open(sample);
}

public void playShootSFX()
{
    shoot.stop();
    shoot.setFramePosition(0);
    shoot.start(); 
}

这篇关于如何在 Java 游戏中播放声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆