Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make PlaySound non-blocking

Tags:

c++

windows

audio

I've been testing sounds and I noticed that PlaySound is blocking, i.e. it waits until the sound has finished playing to return.

#include <iostream>
#include <Windows.h>
#include <mmsystem.h>

int main()
{
    PlaySound("E:/Downloads/eb_sfx_archive/brainshock.wav", 0, SND_FILENAME);
    std::cout << "this sound is cool";
    Sleep (500);
    std::cout << "\nmeh... not really";
    return 0;
}

This code plays the sound, but it waits to output "this sound is cool" until after the sound has finished playing. How can I make it not do that?

like image 612
Jeff Nilsson Avatar asked Oct 28 '25 05:10

Jeff Nilsson


2 Answers

Play the sound asynchronously:

PlaySound(L"E:\\Downloads\\eb_sfx_archive\\brainshock.wav", NULL, SND_ASYNC);

From the MSDN documentation:

The sound is played asynchronously and PlaySound returns immediately after beginning the sound. To terminate an asynchronously played waveform sound, call PlaySound with pszSound set to NULL.

Play the sound asynchronously using the flag SND_ASYNC.

I.e:

PlaySound("E:/Downloads/eb_sfx_archive/brainshock.wav", 0, SND_FILENAME | SND_ASYNC);

The SND_ASYNC flag causes PlaySound to return immediately without waiting for the sound to finish playing.

Also, if you need to stop playing a sound (looped or asynchronous) without playing another sound, use the following statement:

PlaySound(NULL, NULL, 0);

More info and examples here (Using PlaySound to Loop Sounds) and here (PlaySound function).

like image 43
Tarod Avatar answered Oct 30 '25 19:10

Tarod



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!