简体   繁体   中英

how to play the media file on timer?

the function playMedia is called again and again inside the timer_tick function for 60 sec...how do i call it just once so that my song plays continuously for that interval without looping.... here song is my media element..

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        timer.Start();
        timer.Tick +=timer_tick;
    }

int flagmusic=0;

public void timer_tick(object sender, object args)
{
  //if some condition which is true for 60 secs
   playMedia();
  //else
  song.stop();
}

 private void playMedia()
    {

         try
         {
                 Uri pathUri = new Uri("ms-appx:///Assets/breath.mp3");
                 song.Source = pathUri;
                 song.Play();
        }
        catch { }

    }

I'm not entirely sure I interpreted your question correctly. As I understand it, when OnNavigatedTo is called, you want to start the song playing, let it play for 60 seconds, and then stop it.

If that's true, I would start by creating my timer at class scope, and initializing it when the program starts:

Timer timer = new Timer();
timer.Tick += timer_tick;
timer.Interval = 60000;
timer.Stop();  // make sure it's not running

In OnNavigatedTo , start the sound and start the timer.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    playMedia();
    timer.Start();
}

So the song is playing and the timer is running. When the timer ticks, stop the song playing and stop the timer.

public void timer_tick(object sender, object args)
{
    timer.Stop();
    song.stop();
}

The reason it was playing the song many times in your original code was that every time OnNavigatedTo was called, the line timer.Tick += timer_tick; was added to the timer event's invocation list. So the first time you call the function, the song was played once. Next time, it was played twice. Then three, four, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM