我正在使用MediaPlayer类(https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/media-playback)在我的UWP项目中播放声音。这一切都在开始时工作正常但突然Play()调用开始“播放”声音(例如PlaybackSession的状态为“正在播放”)但没有声音输出......
Dictionary<string, MediaPlayer> Effects = new Dictionary<string, MediaPlayer>();
public async Task LoadEffects()
{
Effects?.Clear();
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("sounds");
foreach (var effect in await folder.GetFilesAsync())
{
MediaPlayer snd = new MediaPlayer();
snd.AutoPlay = false;
snd.Source = MediaSource.CreateFromStorageFile(effect);
snd.RealTimePlayback = true;
snd.AudioCategory = MediaPlayerAudioCategory.GameMedia;
Effects.Add(effect.DisplayName, snd);
}
IsLoaded = true;
}
public void StartPlaying(string name, float volume = 1.0f, bool force = false)
{
lock (_instance)
{
if (Effects.ContainsKey(name))
{
//if force is true, force the sound to stop and play again otherwise just exit
if (Effects[name].PlaybackSession.PlaybackState == MediaPlaybackState.Playing && !force)
{
return;
}
Effects[name].Pause();
Task.Delay(100).ContinueWith((res) =>
{
Effects[name].Volume = volume;
Effects[name].PlaybackSession.Position = TimeSpan.Zero;
Effects[name].IsLoopingEnabled = true;
Effects[name].Play();
});
}
}
}
public void StopPlaying(string name)
{
lock (_instance)
{
try
{
//if nothing is playing just return
if (Effects[name].PlaybackSession.PlaybackState != MediaPlaybackState.Playing) return;
}
catch(Exception ex)
{
//weird error happens sometimes, catch it and just return
return;
}
if (Effects.ContainsKey(name))
{
Debug.WriteLine($"Stopping {name} now; state before: {Effects[name].PlaybackSession.PlaybackState.ToString()}");
Effects[name].IsLoopingEnabled = false;
Effects[name].Pause();
Effects[name].PlaybackSession.Position = TimeSpan.Zero;
}
}
}
我注意到,当我没有使用Task.Delay()时,它似乎更频繁地发生。 使用了锁,因为我有一个单例类。