Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an image, then wait a few seconds, then play a mp3 sound?

Tags:

c#

picturebox

After pressing a button, I would like to show an image (using a picturebox), wait a few seconds and then play a mp3 sound, but i dont get it to work. To wait a few seconds I use System.Threading.Thread.Sleep(5000). The problem is, the image always appears after the wait time, but I want it to show first, then wait, then play the mp3... I tried to use WaitOnLoad = true but it doesn't work, shouldn't it load the image first and the continue to read the next code line?

Here is the code I've tried (that doesn't work):

private void button1_Click(object sender, EventArgs e) {
    pictureBox1.WaitOnLoad = true;
    pictureBox1.Load("image.jpg");
    System.Threading.Thread.Sleep(5000);
    MessageBox.Show("test");//just to test, here should be the code to play the mp3
}

I also tried loading the image with "LoadAsync" and put the code to wait and play the mp3 in the "LoadCompleted" event, but that doesn't work either...

like image 248
ibmkahm Avatar asked Jan 31 '26 00:01

ibmkahm


1 Answers

I would use the LoadCompleted event and start a timer with 5 sec interval once the image is loaded, so that the UI thread is not blocked:

   private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.WaitOnLoad = false;
        pictureBox1.LoadCompleted += new AsyncCompletedEventHandler(pictureBox1_LoadCompleted);
        pictureBox1.LoadAsync("image.jpg");
    }

    void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
    {
        //System.Timers.Timer is used as it supports multithreaded invocations
        System.Timers.Timer timer = new System.Timers.Timer(5000); 

        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

        //set this so that the timer is stopped once the elaplsed event is fired
        timer.AutoReset = false; 

        timer.Enabled = true;
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        MessageBox.Show("test"); //just to test, here should be the code to play the mp3
    }
like image 60
Petar Kabashki Avatar answered Feb 02 '26 13:02

Petar Kabashki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!