daniyalahmad
daniyalahmad

Reputation: 3863

Delay in for loop while playing mp3 file C#

I want to give delay in for loop, While in for loop there is mp3 file is playing. What I actually want to do, that every clip plays after 2 sec. There are total 10 clips. Here is my code

    for (int i=1; i < 10; i++)
        {
            System.Threading.Thread.Sleep(1000);
            WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

            wplayer.URL = @"D:\Project C#\A-Z\" + i + ".mp3";

        }

Upvotes: 0

Views: 1360

Answers (1)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26219

1000 millisceconds = 1 sec. so change your code as below:

for (int i=1; i < 10; i++)
        {
            System.Threading.Thread.Sleep(2000);
            WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

            wplayer.URL = @"D:\Project C#\A-Z\" + i + ".mp3";

        }

Adding Timer would solve your Problem:

Step 1: Add a Timer object to your class as below:

Timer timerPlay = new Timer();

Step 2:

write a function to play the audio files.

private void playMyAudioFile(object sender,EventArgs e)
        {
           //code for playing your audio file
        }

Step 3: subscribe the above function to the TimerTick event as below:

 this.timerPlay.Tick += new System.EventHandler(this.playMyAudioFile);

functions which are subscribed to Tick event are notified/called for every Tick event of Timer.

Step 4: now set the Timer Interval as 2 seconds. so that Timer will generate the Tick event for every 2 seconds.

 timerPlay.Interval = 2000;

Step 5:

here you can control the Timer by calling Start() and Stop() Methods.

start the timer by calling:

timerPlay.Start();

stop the timer by calling:

timerPlay.Stop();

Upvotes: 2

Related Questions