0

i am using the background audio player to play an audio file.I have tried to get the duration of the audio using the background.instance.track.duration.totalseconds method.But when i run the app method returned "0" everytime.The duration is retrieved if i run the code through breakpoints. Below is my code.

   if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Playing)
            {

                progressBar1.Visibility = System.Windows.Visibility.Visible;
                TotalTimeDisplay.Visibility = System.Windows.Visibility.Visible;
                //this.TotalTimeDisplay.Time = TimeSpan.Parse("00:00:00.0");
                imgplay.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Images/player_pause_new.png", UriKind.Relative));
                AudioTrack audioTrack = new AudioTrack(new Uri("a" + imgname + ".MP3", UriKind.Relative), "", "", "", null);
                BackgroundAudioPlayer.Instance.Track = audioTrack;
                duration = BackgroundAudioPlayer.Instance.Track.Duration.TotalMilliseconds;
         }

Please suggest the solution .Thanks in advance.

Shawn Kendrot
  • 12,425
  • 1
  • 25
  • 41

2 Answers2

1

Try

BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);

then

   void Instance_PlayStateChanged(object sender, EventArgs e)
   {
       int duration = (sender as BackgroundAudioPlayer).Track.Duration.TotalMilliseconds;
   }

I do not know why...but it should start

Spode
  • 33
  • 8
0

In the original code snippet you are asking for the length of the track immediately after having set the track to be played. With high likelihood the background audio player system has not had chance to set itself up and find the length of the track etc. So at that point you will get zero length. However, if you are manually stepping through the code in debugger you will typically be slow enough to give the system time to get set up and therefore you will get the length right. The use of PlayStateChanged event as suggested above resolves the problem in a natural way.

juhariis
  • 568
  • 8
  • 15