aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/SoundUtils.kt
blob: 9eb476666a78358f78d6bfb14057cc4e484c6304 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package at.hannibal2.skyhanni.utils

import net.minecraft.client.Minecraft
import net.minecraft.client.audio.ISound
import net.minecraft.client.audio.PositionedSound
import net.minecraft.client.audio.SoundCategory
import net.minecraft.util.ResourceLocation

object SoundUtils {
    private val beepSound by lazy { createSound("random.orb", 1f) }

    fun ISound.playSound() {
        val gameSettings = Minecraft.getMinecraft().gameSettings
        val oldLevel = gameSettings.getSoundLevel(SoundCategory.PLAYERS)
        gameSettings.setSoundLevel(SoundCategory.PLAYERS, 1f)
        try {
            Minecraft.getMinecraft().soundHandler.playSound(this)
        } catch (e: Exception) {
            if (e is IllegalArgumentException) {
                e.message?.let {
                    if (it.startsWith("value already present:")) {
                        println("SkyHanni Sound error: $it")
                        return
                    }
                }
            }
            e.printStackTrace()
        } finally {
            gameSettings.setSoundLevel(SoundCategory.PLAYERS, oldLevel)
        }
    }

    fun createSound(name: String, pitch: Float): ISound {
        val sound: ISound = object : PositionedSound(ResourceLocation(name)) {
            init {
                volume = 50f
                repeat = false
                repeatDelay = 0
                attenuationType = ISound.AttenuationType.NONE
                this.pitch = pitch
            }
        }
        return sound
    }

    fun playBeepSound() {
        beepSound.playSound()
    }
}