// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Audio.Track; using osu.Framework.Graphics; using osu.Framework.Threading; namespace osu.Game.Audio { public abstract class PreviewTrack : Component { /// /// Invoked when this has stopped playing. /// public event Action Stopped; /// /// Invoked when this has started playing. /// public event Action Started; private Track track; private bool hasStarted; [BackgroundDependencyLoader] private void load() { track = GetTrack(); track.Completed += () => Schedule(Stop); } /// /// Length of the track. /// public double Length => track?.Length ?? 0; /// /// The current track time. /// public double CurrentTime => track?.CurrentTime ?? 0; /// /// Whether the track is loaded. /// public bool TrackLoaded => track?.IsLoaded ?? false; /// /// Whether the track is playing. /// public bool IsRunning => track?.IsRunning ?? false; private ScheduledDelegate startDelegate; /// /// Starts playing this . /// public void Start() => startDelegate = Schedule(() => { if (track == null) return; if (hasStarted) return; hasStarted = true; track.Restart(); Started?.Invoke(); }); /// /// Stops playing this . /// public void Stop() { startDelegate?.Cancel(); if (track == null) return; if (!hasStarted) return; hasStarted = false; track.Stop(); Stopped?.Invoke(); } /// /// Retrieves the audio track. /// protected abstract Track GetTrack(); } }