0

I am making Windows 8 Metro style app. I want to be able to run different sounds at the same time and manage them. For this goals I have created MediaPlayService which should contain methods which allow me to do that.

I found one issue that after "_mediaElement.SetSource()" I can not change volume. I am calling SetVolume and nothing happen.

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();
             }
  }
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Illia
  • 1
  • 2

1 Answers1

0

Your MediaElement isn't part of the VisualTree of your page. As consequence you have to deal with those strange behaviors like setting the volume or position won't work correctly.

As solution you might create the MediaElement in your XAML file or add it from your code-behind to the VisualTree (something like contentGrid.Children.Add( _mediaElement ). In the latter case you probably have to remove it before navigating to another page else it might happen that it won't play the next time you are navigating back.

Sven Meyer
  • 36
  • 3