1
0
mirror of https://github.com/ppy/osu.git synced 2024-11-06 06:57:39 +08:00
osu-lazer/osu.Game/Audio/PreviewTrack.cs

113 lines
2.8 KiB
C#
Raw Normal View History

2018-05-25 05:37:53 +08:00
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Allocation;
2018-05-25 05:37:53 +08:00
using osu.Framework.Audio.Track;
using osu.Framework.Graphics;
using osu.Framework.Threading;
2018-05-25 05:37:53 +08:00
namespace osu.Game.Audio
{
public abstract class PreviewTrack : Component
2018-05-25 05:37:53 +08:00
{
2018-06-21 17:54:42 +08:00
/// <summary>
/// Invoked when this <see cref="PreviewTrack"/> has stopped playing.
/// </summary>
2018-05-25 05:37:53 +08:00
public event Action Stopped;
2018-06-21 17:54:42 +08:00
/// <summary>
/// Invoked when this <see cref="PreviewTrack"/> has started playing.
/// </summary>
2018-05-25 05:37:53 +08:00
public event Action Started;
private Track track;
private bool wasPlaying;
[BackgroundDependencyLoader]
private void load()
2018-05-25 05:37:53 +08:00
{
track = GetTrack();
if (track != null)
track.Looping = false;
2018-05-25 05:37:53 +08:00
}
/// <summary>
/// Length of the track.
/// </summary>
public double Length => track?.Length ?? 0;
/// <summary>
/// The current track time.
/// </summary>
public double CurrentTime => track?.CurrentTime ?? 0;
/// <summary>
/// Whether the track is loaded.
/// </summary>
public bool TrackLoaded => track?.IsLoaded ?? false;
2018-06-21 18:31:07 +08:00
/// <summary>
/// Whether the track is playing.
/// </summary>
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;
2018-06-21 17:54:42 +08:00
/// <summary>
/// Starts playing this <see cref="PreviewTrack"/>.
/// </summary>
public void Start() => startDelegate = Schedule(() =>
2018-05-25 05:37:53 +08:00
{
if (!IsLoaded)
return;
if (track == null)
return;
if (wasPlaying)
return;
wasPlaying = true;
track.Restart();
2018-05-25 05:37:53 +08:00
Started?.Invoke();
});
2018-05-25 05:37:53 +08:00
2018-06-21 17:54:42 +08:00
/// <summary>
/// Stops playing this <see cref="PreviewTrack"/>.
/// </summary>
public void Stop()
2018-05-25 05:37:53 +08:00
{
startDelegate?.Cancel();
if (!IsLoaded)
return;
if (track == null)
2018-06-03 03:06:45 +08:00
return;
if (!wasPlaying)
return;
wasPlaying = false;
track.Stop();
2018-05-25 05:37:53 +08:00
Stopped?.Invoke();
}
2018-06-21 17:54:42 +08:00
/// <summary>
/// Retrieves the audio track.
/// </summary>
protected abstract Track GetTrack();
2018-05-25 05:37:53 +08:00
}
}