Is there any way to set the respective volume of a Clip in Java?

I have this method:

public static void play(Clip clip) {

if (Settings.getSettings().isVolumeOn()) {

FloatControl volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);

volume.setValue(-1 * Settings.getSettings().getVolume());

clip.start();

}

}

The Settings.getSettings().getVolume() returns an Integer in the range of 0 - 100

Volumes:

0 : No Sound

40 : Optimal Sound with headphones

60 : Optimal Sound

100: Full Sound

So essentially this should be like the scale of VLC (but half since VLC is from 0 to 200).

I've found that I can reduce the decibel of the clip by using volume.setValue(-10f);

But I would prefer something of the type volume.setValue(clip.getMaxVolume() * Settings.getSettings().getVolume()/100).

Where clip.getMaxVolume() would return the max volume of the clip.

解决方案

According to Killer Game Programming by Andrew Davison you can adjust volume this simple:

float range = gainControl.getMaximum() - gainControl.getMinimum();

float gain = (range * volume) + gainControl.getMinimum();

gainControl.setValue(gain);

volume being the desired volume in float (0.0f means no sound, 1.0f means full audio)

gainControl is the FloatControl

Hope you can get it to work!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐