简体   繁体   English

如何在计时器上播放媒体文件?

[英]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.. 该函数playMedia在timer_tick函数内一次又一次地调用60秒钟...我如何一次调用它,以便我的歌曲在该间隔内连续播放而不循环。...这首歌是我的媒体元素。

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. 据我了解,调用OnNavigatedTo时,您要开始播放歌曲,让其播放60秒,然后停止播放。

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. OnNavigatedTo ,启动声音并启动计时器。

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; 它在您的原始代码中多次播放歌曲的原因是,每次调用OnNavigatedTo时,都会使用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. 然后是三,四等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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