1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-25 03:22:57 +08:00
osu-lazer/osu.Game/Skinning/PausableSkinnableSound.cs

98 lines
2.7 KiB
C#
Raw Normal View History

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
2022-06-17 15:37:17 +08:00
#nullable disable
using System.Collections.Generic;
using System.Linq;
2020-11-19 19:38:36 +08:00
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Threading;
using osu.Game.Audio;
namespace osu.Game.Skinning
{
public class PausableSkinnableSound : SkinnableSound
{
public double Length => !DrawableSamples.Any() ? 0 : DrawableSamples.Max(sample => sample.Length);
2021-04-20 15:51:00 +08:00
public bool RequestedPlaying { get; private set; }
2020-11-19 19:38:36 +08:00
public PausableSkinnableSound()
{
}
2020-11-19 19:38:36 +08:00
public PausableSkinnableSound([NotNull] IEnumerable<ISampleInfo> samples)
2020-11-19 18:51:09 +08:00
: base(samples)
{
}
2020-11-19 19:38:36 +08:00
public PausableSkinnableSound([NotNull] ISampleInfo sample)
: base(sample)
{
}
private readonly IBindable<bool> samplePlaybackDisabled = new Bindable<bool>();
private ScheduledDelegate scheduledStart;
[BackgroundDependencyLoader(true)]
private void load(ISamplePlaybackDisabler samplePlaybackDisabler)
{
// if in a gameplay context, pause sample playback when gameplay is paused.
if (samplePlaybackDisabler != null)
{
samplePlaybackDisabled.BindTo(samplePlaybackDisabler.SamplePlaybackDisabled);
samplePlaybackDisabled.BindValueChanged(SamplePlaybackDisabledChanged);
}
}
protected virtual void SamplePlaybackDisabledChanged(ValueChangedEvent<bool> disabled)
{
if (!RequestedPlaying) return;
// let non-looping samples that have already been started play out to completion (sounds better than abruptly cutting off).
if (!Looping) return;
cancelPendingStart();
if (disabled.NewValue)
base.Stop();
else
{
// schedule so we don't start playing a sample which is no longer alive.
scheduledStart = Schedule(() =>
{
if (RequestedPlaying)
base.Play();
});
}
}
2021-01-19 16:11:40 +08:00
public override void Play()
{
cancelPendingStart();
RequestedPlaying = true;
if (samplePlaybackDisabled.Value)
return;
2021-01-19 16:11:40 +08:00
base.Play();
}
public override void Stop()
{
cancelPendingStart();
RequestedPlaying = false;
base.Stop();
}
private void cancelPendingStart()
{
scheduledStart?.Cancel();
scheduledStart = null;
}
}
}