// Copyright (c) 2007-2018 ppy Pty Ltd . // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE 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(); } /// /// 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; protected override void Update() { base.Update(); // Todo: Track currently doesn't signal its completion, so we have to handle it manually if (hasStarted && track.HasCompleted) Stop(); } 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(); } }