1
0
mirror of https://github.com/ppy/osu.git synced 2024-09-22 00:47:24 +08:00
osu-lazer/osu.Game/Audio/PreviewTrack.cs

108 lines
2.7 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;
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
}
}