// 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 wasPlaying; [BackgroundDependencyLoader] private void load() { track = GetTrack(); if (track != null) track.Looping = false; } /// /// 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 (track != null && wasPlaying && track.HasCompleted) Stop(); } private ScheduledDelegate startDelegate; /// /// Starts playing this . /// public void Start() => startDelegate = Schedule(() => { if (!IsLoaded) return; if (track == null) return; if (wasPlaying) return; wasPlaying = true; track.Restart(); Started?.Invoke(); }); /// /// Stops playing this . /// public void Stop() { startDelegate?.Cancel(); if (!IsLoaded) return; if (track == null) return; if (!wasPlaying) return; wasPlaying = false; track.Stop(); Stopped?.Invoke(); } /// /// Retrieves the audio track. /// protected abstract Track GetTrack(); } }