0

I'm trying to make a GUI that first plays a sound file after clicking a button and after playing it, it starts a timer.

Now the easiest way I found to get this behaviour is to play the sound file synchronously inside the GUI. This way the GUI 'Blocks' and only starts the timer after the sound file has finished playing.

Here is the problem:

I didn't anticipate the sound file to be this long but some are quite lengthy and cause the GUI to display 'Program not responding'.

Now what can I do to still start the timer after playing the sound but not getting the GUI locked?

I was thinking of using a Task but checking whether the task is completed will still probably lock the GUI.

What can I do to make this work?

UPDATE:

This code runs in an other Thread, to get the timer started in the GUI the following code is used (using the solution provided by Marc Gravell found here)

        //start timer after playing sound source:
        this.Invoke((MethodInvoker)delegate
        {
            if (!timer.Enabled)
                timer.Start();
        });
Community
  • 1
  • 1
Devenda
  • 3
  • 2

2 Answers2

1

Very simple task using threads.Here is an example how you can accomplish this:

private void button1_Click(object sender, EventArgs e)
    {
        new System.Threading.Thread(testMethod).Start(); //starting a new thread
    }

    public void testMethod() //method will play sound and start timer after that
    {
        System.Media.SoundPlayer sp = new System.Media.SoundPlayer(filepath);
        sp.Play();
        timer1.Start();
    }
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • A [Task](http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx) or a [Threadpool thread](http://msdn.microsoft.com/en-us/library/kbf0f1ct.aspx) may be a better choice if you are going to be doing this a lot to reduce resource usage. – Scott Chamberlain Oct 05 '13 at 20:51
  • I can't try it out right now but this will certainly work, ill try it first thing in the morning! – Devenda Oct 05 '13 at 21:28
  • I just tried it out but it does not seem to work, the sound plays fine but the timer (in the GUI) does not start... It is as if that it only get started in the Thread but not in the GUI – Devenda Oct 06 '13 at 10:45
  • I updated my post with working code, this code starts the timer in the GUI (first Thread). – Devenda Oct 06 '13 at 11:38
0

Use threads. when the button is pressed, start the timer in a thread. this thread should stop the sound. the thread would not block your UI or making it NOT responding.

Tauseef
  • 2,035
  • 18
  • 17