简体   繁体   中英

Custom .wav file in c# windows form application every second

I am having some trouble playing a 4second long wave... What I am currently doing is running a timer....

So the timer is set to a second intervals... So every second, I run off and check something... If this check fails.. I play a wav file saying "Get back to work!"...

Currently, it pauses the timer.... So I hear "Get back to work" but while it is playing, I have lost 4 seconds of count time, because it is still finishing playing the sound.... Here is my call and my function...

playSimpleSound();

    private void playSimpleSound()
    {
        SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\shortwav.wav");
        simpleSound.PlaySync();
    }

If I switch them out, so that it actually plays everytime it hits.... I only hear the beginning of the wav file....

playSimpleSound();

    private void playSimpleSound()
    {
        SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\shortwav.wav");
        simpleSound.Play();
    }

So my question is...

How can I continue counting, and play the whole wav file? Should I figure out how long the wav file is and then go ahead and do some kind of count with a mod on it?

So that I basically only play the file every x amount of seconds or something?

So basically just call the playsound function everytime, but inside that function count how many times it has been visited and only play it on the 4th second?

You could do something like this...play the sound on a different thread and toggle a flag:

public partial class Form1 : Form
{

    private SoundPlayer simpleSound; 
    private bool SoundPlaying = false;

    public Form1()
    {
        InitializeComponent();
        this.Load += Form1_Load;
    }

    void Form1_Load(object sender, EventArgs e)
    {
        simpleSound = new SoundPlayer(@"c:\Windows\Media\shortwav.wav");
        simpleSound.LoadAsync();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Console.WriteLine("Tick");
        if (true) // check your condition
        {
            this.PlaySound();
        }
    }

    private void PlaySound()
    {
        if (!this.SoundPlaying)
        {
            Console.WriteLine("Starting Sound");
            this.SoundPlaying = true;
            Task.Factory.StartNew(() => {
                simpleSound.PlaySync();
                this.SoundPlaying = false;
            });
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM