1

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

    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
4

1 回答 1

1

DispatcherTimer.Interval 是 Tick 事件之间经过的最短时间。通常它更多。您应该在开始时使用 _startTime = DateTime.Now 之类的东西,然后再使用 _runningTime = DateTime.Now - _startTime。在测量 _startTime 之前,您可能还希望等待 musicPlayer.CurrentStateChanged 直到 musicPlayer.CurrentState == MediaElementState.Playing。

再说一遍 - 为什么不把 musicPlayer.Position 作为你的 _runningTime 值呢?

于 2012-08-10T18:50:28.050 回答