我正在使用BackgroundAudioTask创建一个UWP应用程序。我的应用程序运行良好。现在我想在TextBlock中添加音频播放的当前位置。
在实现音频任务之前,我正在执行此方法:
private TimeSpan TotalTime;
private DispatcherTimer timerRadioTime;
private void radioPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
TotalTime = radioPlayer.NaturalDuration.TimeSpan;
// Create a timer that will update the counters and the time slider
timerRadioTime = new DispatcherTimer();
timerRadioTime.Interval = TimeSpan.FromSeconds(1);
timerRadioTime.Tick += TimerRadioTime_Tick;
timerRadioTime.Start();
}
private void TimerRadioTime_Tick(object sender, object e)
{
//Check if the audio finished calculate it's total time
if (radioPlayer.NaturalDuration.TimeSpan.TotalSeconds > 0)
{
if (TotalTime.TotalSeconds > 0)
{
// Updating timer
TimeSpan currentPos = radioPlayer.Position;
var currentTime = string.Format("{0:00}:{1:00}", (currentPos.Hours * 60) + currentPos.Minutes, currentPos.Seconds);
radioTimerBlock.Text = currentTime;
}
}
}
当我实现后台任务时,它给了我一个例外。在研究之后,我看到了使用ThreadPoolTimer而不是dispatcherTimer的建议。
我尝试编写此代码(遵循此解决方案:Clock program employing ThreadPoolTimer C# uwp)
ThreadPoolTimer timer;
// for displaying time only
private void CurrentPlayer_MediaOpened(MediaPlayer sender, object args)
{
_clockTimer_Tick(timer);
}
private async void _clockTimer_Tick(ThreadPoolTimer timer)
{
var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
await dispatcher.RunAsync(
CoreDispatcherPriority.Normal, () =>
{
// Your UI update code goes here!
if (CurrentPlayer.NaturalDuration.TotalSeconds > 0)
{
TimeSpan currentPos = CurrentPlayer.Position;
var currentTime = string.Format("{0:00}:{1:00}", (currentPos.Hours * 60) + currentPos.Minutes, currentPos.Seconds);
CurrentPosition.Text = currentTime;
}
});
}
这显然不起作用。应用程序在不更新我的UI的情况下输入方法。我真的不明白timer
应该是什么。关于如何让它运行的任何想法?
答案 0 :(得分:1)
解决方案:
ThreadPoolTimer timer;
// for displaying time only
private void CurrentPlayer_MediaOpened(MediaPlayer sender, object args)
{
timer = ThreadPoolTimer.CreatePeriodicTimer(_clockTimer_Tick, TimeSpan.FromSeconds(1));
}
private async void _clockTimer_Tick(ThreadPoolTimer timer)
{
var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
await dispatcher.RunAsync(
CoreDispatcherPriority.Normal, () =>
{
// Your UI update code goes here!
if (CurrentPlayer.NaturalDuration.TotalSeconds < 0)
{
TimeSpan currentPos = CurrentPlayer.Position;
var currentTime = string.Format("{0:00}:{1:00}", (currentPos.Hours * 60) + currentPos.Minutes, currentPos.Seconds);
CurrentPosition.Text = currentTime;
}
});
}