2012-08-10 90 views
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 
+0

爲什麼mod 60?運行時間(毫秒)/ 1000不會在幾秒內讓你獲得運行時間? – 2012-08-10 16:49:00

+0

musicPlayer只給了我位置的秒部分。所以在1:26它會給我26.我在模擬60上的運行時間,所以它會匹配。 – connor 2012-08-10 16:51:20

+0

好的,這很有道理。那麼我的猜測是'musicPlayer.Play()'可能有一些初始化/緩衝/加載等等,它在開始真正播放之前需要做。它落後多遠? – 2012-08-10 16:53:47

回答

1

DispatcherTimer.Interval是時間的最低金額,將蜱事件之間傳遞的。通常是更多。你應該在開始時使用類似_startTime = DateTime.Now的事情,然後再做_runningTime = DateTime.Now - _startTime。在測量_startTime之前,您可能還想等待musicPlayer.CurrentStateChanged,直到musicPlayer.CurrentState == MediaElementState.Playing。

話又說回來 - 爲什麼不乾脆讓musicPlayer.Position爲您_runningTime價值?