aboutsummaryrefslogtreecommitdiff
path: root/source/game/music/MusicManager.cs
blob: 8d9f9f56735c3a42dc125052f4523173d3084e8e (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
50
51
52
53
54
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;

namespace Celesteia.Game.Music {
    public class MusicManager : GameComponent {
        private new GameInstance Game => (GameInstance) base.Game;
        public MusicManager(GameInstance Game) : base(Game) {}

        private float SetVolume = 0.1f;
        private float _volume;
        private Song _nextUp;
        private float _elapsedTransitionTime;
        private float _transitionDuration = 2f;
        private bool _transitionComplete = false;

        public override void Update(GameTime gameTime)
        {
            if (_elapsedTransitionTime >= _transitionDuration) _volume = 1f;
            else {
                _elapsedTransitionTime += ((float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000f);

                if (_elapsedTransitionTime >= _transitionDuration / 2f && !_transitionComplete) {
                    if (_nextUp != null) {
                        MediaPlayer.Play(_nextUp);
                        _nextUp = null;
                    } else Stop();
                    
                    _transitionComplete = true;
                }

                _volume = Volume(_elapsedTransitionTime);
            }

            MediaPlayer.Volume = _volume * SetVolume;
        }

        public void PlayNow(Song song, bool repeat = true) {
            MediaPlayer.IsRepeating = repeat;

            _elapsedTransitionTime = MediaPlayer.State == MediaState.Playing ? 0f : 1f;
            _transitionComplete = false;
            _nextUp = song;
        }

        public void Stop() {
            MediaPlayer.Stop();
        }

        private float Volume(float x) {
            return Math.Abs(x - (_transitionDuration / 2f));
        }
    }
}