节目时间与音乐时间

时间:2012-08-10 16:44:57

标签: c# performance time microsoft-metro

我一直在努力制作一款带有音乐的游戏。我一直在使用计时器来跟踪程序的运行时间,但是我无法将音乐的播放时间与我的程序的运行时间相匹配。即使我几乎摆脱了所有代码,它仍然会变慢。这就是我的代码所在。

    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

1 个答案:

答案 0 :(得分:1)

DispatcherTimer.Interval是Tick事件之间传递的最短时间。通常它更多。您应该在开头使用类似_startTime = DateTime.Now的内容,然后执行_runningTime = DateTime.Now - _startTime。在测量_startTime之前,您可能还需要等待musicPlayer.CurrentStateChanged,直到musicPlayer.CurrentState == MediaElementState.Playing。

然后再次 - 为什么不将musicPlayer.Position作为_runningTime值?