-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSetting.cs
62 lines (47 loc) · 1.61 KB
/
Setting.cs
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
50
51
52
53
54
55
56
57
58
59
60
61
62
using Godot;
using System;
public partial class Setting : Control
{
private HSlider volumeSlider;
private Label volumeLabel;
private const string ConfigFilePath = "user://settings.cfg";
private const string VolumeKey = "audio/master_volume";
public override void _Ready()
{
volumeSlider = GetNode<HSlider>("VBoxContainer/VolumeSlider");
volumeLabel = GetNode<Label>("VBoxContainer/VolumeLabel");
double initialVolume = LoadVolume();
volumeSlider.Value = initialVolume;
float volumeDb = Mathf.LinearToDb((float)(initialVolume / 100.0));
AudioServer.SetBusVolumeDb(AudioServer.GetBusIndex("Master"), volumeDb);
volumeLabel.Text = $"Master Volume: {(int)volumeSlider.Value}%";
volumeSlider.ValueChanged += _on_volume_slider_value_changed;
}
private void _on_volume_slider_value_changed(double value)
{
float volumeDb = Mathf.LinearToDb((float)(value / 100.0));
AudioServer.SetBusVolumeDb(AudioServer.GetBusIndex("Master"), volumeDb);
volumeLabel.Text = $"Master Volume: {(int)value}%";
SaveVolume(value);
}
private void SaveVolume(double value)
{
ConfigFile configFile = new ConfigFile();
configFile.Load(ConfigFilePath);
configFile.SetValue("Audio", VolumeKey, value);
configFile.Save(ConfigFilePath);
}
private double LoadVolume()
{
ConfigFile configFile = new ConfigFile();
Error err = configFile.Load(ConfigFilePath);
if (err == Error.Ok)
{
if (configFile.HasSectionKey("Audio", VolumeKey))
{
return (double)configFile.GetValue("Audio", VolumeKey);
}
}
return Mathf.DbToLinear((float)AudioServer.GetBusVolumeDb(AudioServer.GetBusIndex("Master"))) * 100.0;
}
}