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

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

问题描述

我用下面的code成功播放声音在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秒间歇延迟。这是pretty差。

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小程序是流的素材,只要你想打它,这就是为什么你得到一个延迟的声音文件还没有被加载到内存然而。

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小应用程序编程,但我不记得我曾经pre-负载我所有的剪​​辑,然后后续调用播放不会重新打开文件。

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.

下面是从我的旧项目的一个部分code

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天全站免登陆