Java剪辑根据距离减少/增加音量

时间:2014-12-13 10:25:40

标签: java audio volume clip

你好我正在写一个游戏,我想根据玩家和演员之间的距离来改变一个演员的音量。我正在循环播放声音。

我的声音课程:

public class Sound {

    private Clip clip;
    private FloatControl volume;

    public Sound(String path) {
        loadMusic(path);
    }

    public void loadMusic(String path) {

        clip = null;
        if (!path.equals("")) {

            File soundFile = null;

            try {
                soundFile = new File(path);
            } catch (Exception e) {
                return;
            }

            try {
                AudioInputStream input = AudioSystem.getAudioInputStream(soundFile);
                clip = AudioSystem.getClip();
                clip.open(input);
            } catch (Exception e) {
                e.printStackTrace();
                clip = null;
            }
            volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);

        }

    }

    public void play() {
        if (clip != null) {
            stop();
            clip.start();
        }
    }

    public void stop() {
        if (clip != null) {
            if (clip.isRunning()) {
                clip.stop();
            }
            clip.setFramePosition(0);
        }
    }

    public void loop() {
        if (clip != null) {
            clip.loop(clip.LOOP_CONTINUOUSLY);
        }
    }

    public void setVolume(float vol) {
        volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
        if (volume.getMinimum() + vol <= volume.getMaximum()) {
            volume.setValue(volume.getMinimum());
            volume.setValue(volume.getMinimum() + vol);
        }
    }
}

这是我检查距离的地方:

public float getDistance(int x, int y) {
        return (float)(Math.sqrt( Math.pow((this.x + this.getWidth() - x), 2) + Math.pow((this.y + this.getHeight() - y), 2)));
    }



//this is checked every loop im game. 
float distance = getDistance(actor.getX() + actor.getWidth(), actor.getY() + actor.getHeight());
    if (distance <= 100) {
        play.setVolume(2000/distance);
    }
    else 
        play.setVolume(0f);

我知道getDistane工作正常,我知道volume.getValue()正在顺利改变,但声音却没有。它更像是在一个循环结束然后它改变音量时等待。

0 个答案:

没有答案