Mindustry/core/src/mindustry/audio/SoundLoop.java

53 lines
1.4 KiB
Java
Raw Normal View History

2020-05-14 09:29:27 +07:00
package mindustry.audio;
2020-11-13 06:07:26 +07:00
import arc.*;
2019-12-25 13:39:38 +07:00
import arc.audio.*;
import arc.math.*;
import arc.util.*;
2019-08-13 10:29:24 +07:00
/** A simple class for playing a looping sound at a position.*/
public class SoundLoop{
2019-08-13 10:29:24 +07:00
private static final float fadeSpeed = 0.05f;
private final Sound sound;
2019-08-15 10:27:24 +07:00
private int id = -1;
2019-08-13 10:29:24 +07:00
private float volume, baseVolume;
public SoundLoop(Sound sound, float baseVolume){
this.sound = sound;
this.baseVolume = baseVolume;
}
public void update(float x, float y, boolean play){
2020-11-09 04:40:32 +07:00
if(baseVolume <= 0) return;
2019-08-13 10:29:24 +07:00
if(id < 0){
if(play){
id = sound.loop(sound.calcVolume(x, y) * volume * baseVolume, 1f, sound.calcPan(x, y));
}
}else{
//fade the sound in or out
if(play){
volume = Mathf.clamp(volume + fadeSpeed * Time.delta);
2019-08-13 10:29:24 +07:00
}else{
volume = Mathf.clamp(volume - fadeSpeed * Time.delta);
2019-08-13 10:29:24 +07:00
if(volume <= 0.001f){
2020-11-13 06:07:26 +07:00
Core.audio.stop(id);
2019-08-13 10:29:24 +07:00
id = -1;
2019-08-14 02:14:03 +07:00
return;
2019-08-13 10:29:24 +07:00
}
}
2020-11-09 04:40:32 +07:00
2020-11-13 06:07:26 +07:00
Core.audio.set(id, sound.calcPan(x, y), sound.calcVolume(x, y) * volume * baseVolume);
2019-08-13 10:29:24 +07:00
}
}
public void stop(){
if(id != -1){
2020-11-13 06:07:26 +07:00
Core.audio.stop(id);
2019-08-13 10:29:24 +07:00
id = -1;
volume = baseVolume = -1;
}
}
}