我一直在尝试制作一个有音乐的游戏。我一直在使用计时器来跟踪程序的运行时间,但我无法将音乐的播放时间与我的程序的运行时间相匹配。即使我摆脱了几乎所有的代码,它仍然很慢。这是我的代码。
int timeInterval;
int runningTime;
DispatcherTimer drawTimer;
public Game()
{
timeInterval = 100;
drawTimer = new DispatcherTimer();
drawTimer.Interval = TimeSpan.FromMilliseconds(timeInterval);
drawTimer.Tick += dispatcherTimer_Tick;
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
runningTime = 0;
StorageFile file;
StorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string filePath = @"soundtrack.m4a";
musicPlayer = new MediaElement();
file = await InstallationFolder.GetFileAsync(filePath);
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
musicPlayer.SetSource(stream, file.ContentType);
musicPlayer.Play();
drawTimer.Start();
}
void dispatcherTimer_Tick(object sender, object e)
{
runningTime += timeInterval;
if ((runningTime / 1000) % 10 == 0)
{
System.Diagnostics.Debug.WriteLine("Music: " + musicPlayer.Position.Seconds + "Running time: " + (runningTime / 1000) % 60);
}
}
谢谢您的帮助。
编辑:这是一些输出
Music: 0Running time: 0
Music: 0Running time: 0
Music: 0Running time: 0
Music: 0Running time: 0
Music: 0Running time: 0
Music: 0Running time: 0
Music: 0Running time: 0
Music: 0Running time: 0
Music: 0Running time: 0
Music: 11Running time: 10
Music: 11Running time: 10
Music: 11Running time: 10
Music: 11Running time: 10
Music: 12Running time: 10
Music: 12Running time: 10
...
Music: 9Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0
Music: 10Running time: 0