2012-06-20 62 views
0

我正在製作Windows 8 Metro風格的應用程序。 我希望能夠同時運行不同的聲音並管理它們。爲了實現這個目標,我創建了MediaPlayService,它應該包含允許我這樣做的方法。Windows 8 Metro應用程序MediaElement.SetSource(在播放過程中無法更改音量)

我在「_mediaElement.SetSource()」後發現了一個問題,我無法更改音量。我打電話給SetVolume,什麼也沒有發生。

Initialize(sound); 
SetVolume(100); 
Play();  --- this sequence works 


Initialize(sound); 
Play();  
SetVolume(100); --- does not work (I can not change the volume during playback) 

public void SetVolume(int volume) 
     { 

      //_m ediaElement.Volume = Math.Round((double)((double)volume/100), 2); 
      double dvolume = Math.Round((double)((double)volume/100), 2); 

      _mediaElement.SetValue(MediaElement.VolumeProperty, dvolume); 

     } 

     string _mediaPath; 

     public void Initialize(Sound sound) 
     { 
      _mediaElement = new MediaElement(); 
      _mediaPath = sound.FilePath; 
      _mediaElement.AudioCategory = Windows.UI.Xaml.Media.AudioCategory.Communications; 
      _mediaElement.IsLooping = true; 
      _mediaElement.MediaFailed += _mediaElement_MediaFailed; 
      _mediaElement.RealTimePlayback = true; 
     } 

     public async void Play() 
     { 

      var pack = Windows.ApplicationModel.Package.Current; 

      var installedLoction = pack.InstalledLocation; 
      var storageFile = await installedLoction.GetFileAsync(_mediaPath); 

      if (storageFile != null) 
      { 
       var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); 
       _mediaElement.SetSource(stream, storageFile.ContentType); 

       _mediaElement.Play(); 
      } 
    } 

回答

0

您的MediaElement不是您網頁的VisualTree的一部分。因此,您必須處理那些奇怪的行爲,例如設置音量或位置將無法正常工作。

作爲解決方案,您可以在您的XAML文件中創建MediaElement或將其從代碼隱藏添加到VisualTree(類似contentGrid.Children.Add(_mediaElement))。在後一種情況下,您可能必須在導航之前將其刪除到另一頁其他頁面可能會發生,它不會在您下次瀏覽時播放。

相關問題