forked from Rampastring/Rampastring.XNAUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundPlayer.cs
More file actions
98 lines (81 loc) · 2.55 KB
/
SoundPlayer.cs
File metadata and controls
98 lines (81 loc) · 2.55 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Rampastring.Tools;
using System;
using System.Collections.Generic;
namespace Rampastring.XNAUI;
/// <summary>
/// A sound player that manages prioritized sounds, with the aim of preventing
/// insignificant sounds from overriding important sounds while still
/// playing insignificant sounds if there's no risk of them cutting off
/// important sounds.
/// </summary>
public class SoundPlayer : GameComponent
{
public SoundPlayer(Game game) : base(game)
{
soundList = new List<PrioritizedSoundInstance>();
}
private static List<PrioritizedSoundInstance> soundList;
public static float Volume { get; private set; } = 1.0f;
public void SetVolume(float volume)
{
Volume = volume;
try
{
MediaPlayer.Volume = volume;
}
catch (Exception ex)
{
Logger.Log("SoundPlayer exception when setting volume: " + ex.Message);
}
}
/// <summary>
/// Plays a sound.
/// </summary>
/// <param name="sound">The sound to play.</param>
public static void Play(EnhancedSoundEffect sound)
{
Play(sound.Volume * Volume, sound);
}
/// <summary>
/// Plays a sound with the specified volume.
/// This overrides the volume setting of the sound itself.
/// </summary>
/// <param name="volume">The volume that the sound will be played at.</param>
/// <param name="sound">The sound to play.</param>
public static void PlayWithVolume(float volume, EnhancedSoundEffect sound)
{
Play(volume * Volume, sound);
}
private static void Play(float volume, EnhancedSoundEffect sound)
{
foreach (var psi in soundList)
{
if (psi.Priority > sound.Priority)
return;
}
var soundInstance = sound.CreateSoundInstance();
if (soundInstance == null)
return;
soundInstance.Volume = volume;
var prioritizedSoundInstance = new PrioritizedSoundInstance(
soundInstance, sound.Priority, sound.PriorityDecayRate);
soundInstance.Play();
soundList?.Add(prioritizedSoundInstance);
}
public override void Update(GameTime gameTime)
{
for (int i = 0; i < soundList.Count; i++)
{
var sound = soundList[i];
if (!sound.Update(gameTime))
{
sound.Dispose();
soundList.RemoveAt(i);
i--;
}
}
base.Update(gameTime);
}
}