Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using UnityEngine;
- namespace JasonStorey.Music
- {
- public class MusicPlayer
- {
- /// <summary>
- /// Pressing Prev in most media players will restart the track if it has been playing a while, but if it is near the start of the track will assume you meant to go back one.
- /// </summary>
- const float PERCENT_PREV_BECOMES_RESTART = 0.1f;
- public void Play()
- {
- if (_source.isPlaying)
- {
- _source.Pause();
- _paused = true;
- }
- else if (_source.clip != null && _paused)
- {
- _source.Play();
- _paused = false;
- }
- }
- public void Play(AudioClip clip)
- {
- if(_source.clip != clip)
- {
- _source.clip = clip;
- OnTrackChanged(_source.clip);
- }
- _source.Play();
- }
- public void Play(Track track)
- {
- CurrentTrack = track;
- Play(track.Clip);
- }
- public void Play(Playlist playlist)
- {
- _currentPlaylist = playlist;
- Play(playlist.Selected);
- }
- public async void Play(string path,AudioType type = AudioType.WAV)
- {
- if (Path.GetExtension(path) == ".mp3")
- {
- Debug.LogWarning($"Cannot stream mp3 files. (Copyright) <color=yellow>{Path.GetFileName(path)}</color> will not play");
- return;
- }
- var clip = await AudioLoader.LoadClipFromPath(path, type);
- Play(clip);
- }
- public void Prev()
- {
- if(PercentThroughCurrentTrack > PERCENT_PREV_BECOMES_RESTART)
- RestartClip();
- else if(_currentPlaylist != null)
- {
- _currentPlaylist.SelectPrev();
- Play(_currentPlaylist);
- }
- }
- public void Next()
- {
- if (_currentPlaylist == null) return;
- _currentPlaylist.SelectNext();
- Play(_currentPlaylist);
- }
- void RestartClip()
- {
- if(_source.isPlaying) _source.Play();
- }
- float PercentThroughCurrentTrack => HasAClip ? _source.clip.length / _source.time : 0;
- public MusicPlayer(AudioSource source) => _source = source;
- readonly AudioSource _source;
- public void UpdateStatus()
- {
- if (_paused) return;
- if (!_source.isPlaying && HasAClip)
- {
- if(_currentPlaylist != null)
- TryPlayingNextPlaylistTrack();
- else
- {
- _source.clip = null;
- OnStopped();
- }
- }
- }
- void TryPlayingNextPlaylistTrack()
- {
- if (_currentPlaylist.AtTheEnd)
- {
- _source.clip = null;
- OnStopped();
- return;
- }
- _currentPlaylist.SelectNext();
- Play(_currentPlaylist);
- }
- public void SeekToPercent(float percent)
- {
- if (!HasAClip) return;
- _source.time = _source.clip.length * percent;
- }
- bool HasAClip => _source.clip != null;
- public Track CurrentTrack { get; private set; }
- protected virtual void OnStopped() => Stopped?.Invoke();
- protected virtual void OnTrackChanged(AudioClip clip)
- {
- if (clip == null) return;
- TrackChanged?.Invoke(clip);
- }
- bool _paused;
- public event Action<AudioClip> TrackChanged;
- public event Action Stopped;
- Playlist _currentPlaylist;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement