This repository has been archived by the owner on Dec 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MusicPlayer.cs
92 lines (75 loc) · 2.24 KB
/
MusicPlayer.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
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
using CAFU.Core.Presentation.View;
using CAFU.Music.Domain.Model;
using CAFU.Music.Domain.UseCase;
using UniRx;
using UnityEngine;
// View ではなく、Domain レイヤにより取り扱われるべきクラスなので、特別な namespace を付与する
namespace CAFU.Music.Domain.Component
{
public class MusicPlayer : MonoBehaviour, IMusicPlayer, IInjectableView<IMusicModel>
{
private IMusicModel MusicModel { get; set; }
private AudioSource AudioSource { get; set; }
private static bool HasInstalled { get; set; }
public static void Install(IMusicModel musicModel)
{
if (HasInstalled)
{
return;
}
var go = new GameObject(typeof(MusicPlayer).Name);
var musicPlayer = go.AddComponent<MusicPlayer>();
musicPlayer.Inject(musicModel);
DontDestroyOnLoad(go);
HasInstalled = true;
}
private void Awake()
{
AudioSource = gameObject.GetComponent<AudioSource>();
if (AudioSource == default(AudioSource))
{
AudioSource = gameObject.AddComponent<AudioSource>();
}
AudioSource.playOnAwake = false;
}
private void OnDestroy()
{
HasInstalled = false;
}
public void Inject(IMusicModel musicModel)
{
MusicModel = musicModel;
MusicModel.MusicPlayer = this;
MusicModel.AudioClip.Subscribe(audioClip => AudioSource.clip = audioClip);
}
public void Play(bool loop = true)
{
AudioSource.loop = loop;
AudioSource.Play();
}
public void Stop()
{
AudioSource.Stop();
}
public void Pause()
{
AudioSource.Pause();
}
public void Resume()
{
AudioSource.UnPause();
}
public void SetVolume(float volume)
{
AudioSource.volume = volume;
}
public void SetPitch(float pitch)
{
AudioSource.pitch = pitch;
}
public bool IsPlaying()
{
return AudioSource.isPlaying;
}
}
}