I've been trying to make a game with music in it. I've been using a timer to keep track of the program's running time but I haven't been able to match up the music's playing time with my program's running time. Even when I get rid of almost all of my code it's still slower. Here's what I have for code.
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);
}
}
Thanks for the help.
Edit: Here's some of the output
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
DispatcherTimer.Interval
is the minimum amount of time that will pass between Tick events. Usually it is more. You should use something like _startTime = DateTime.Now
at the beginning and later do _runningTime = DateTime.Now - _startTime
. You might also want to wait for musicPlayer.CurrentStateChanged
until musicPlayer.CurrentState == MediaElementState.Playing
before measuring the _startTime
.
Then again - why not just get musicPlayer.Position
as your _runningTime
value?