Search code examples
c#for-loopthread-sleepwmplib

C# - I want my player to delay 2 seconds before playing any file and repeat it in the loop(For)


Hi I have written the following code but only once plays the audio file after it leaves the "dataGridView1_CellClick" event. I want to know:


1) Can I be able to play sound within the event?


2) Can I repeat the broadcast without using "Player.settings.playCount" ? Because this code can not be delayed before the release of each file. Thanks

My Code Is:

WMPLib.WindowsMediaPlayer Player = new WMPLib.WindowsMediaPlayer();

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{

    //...

    //********** Play audio of Word
    // sVoicePath = @"C:\4536.mp3"
      sVoicePath = Application.StartupPath + dataGridView1.CurrentRow.Cells[4].Value.ToString();
      PlayFile(sVoicePath);
    //...
}

//*****************************
private void PlayFile(String url)
        {
            for (int i = 0; i < 3 ;i++)
            {
                System.Threading.Thread.Sleep(2000);
                Player.URL = url;
                Player.controls.play();
            }
        }
//*****************************
        private void Player_PlayStateChange(int NewState)
        {
            if ((WMPLib.WMPPlayState)NewState == 
                    WMPLib.WMPPlayState.wmppsStopped)
            {
                //Actions on stop
            }
        }

Solution

  • You can use Microsoft's Reactive Framework (aka Rx). NuGet System.Reactive and add using System.Reactive.Linq to your code. Then you can do this:

    private void PlayFile(String url)
    {
        Observable
            .Interval(TimeSpan.FromSeconds(1.0))
            .Take(3)
            .Subscribe(x =>
            {
                Player.URL = url;
                Player.controls.play();
            });
    }