Devenda
Devenda

Reputation: 3

Start timer after playing sound file and avoid locking GUI

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();
        });

Upvotes: 0

Views: 201

Answers (2)

Shaharyar
Shaharyar

Reputation: 12439

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();
    }

Upvotes: 1

Tauseef
Tauseef

Reputation: 2052

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.

Upvotes: 0

Related Questions