Search code examples
c++audioconsole

PlaySound in C++ Console application?


EDITED SO THE CODE IS CORRECT (THANKS TO ta.speot.is) - NEW QUESTION AT BOTTOM

So I have been playing with the console as I am at that level, and we have been asked to make our first "project" for a assessment. I have the basic application all done.. but i wanted to jaz it up a bit and add some sounds. Sounds that will play from the console.

This test works(kind of), as it will play a sound file, but there are 2 problems...

  1. When the sound starts playing, the application freezes until it finishes playing.

  2. When I try to compile as a "release" it errors with a "linking error" - fatal error LNK1120: 1 unresolved externals.

#include <iostream>
#include <windows.h>
#include <mmsystem.h>
using namespace std;

int main(){
    //PlaySound(TEXT("mywavsound.wav"), NULL, SND_FILENAME); - My erroring code
    PlaySound(TEXT("mywavsound.wav"), NULL, SND_FILENAME | SND_ASYNC);// - the correct code
        
    int test = 0;
    cin>>test;
    return 0;
}

So my questions are...

  1. How can I play sounds without freezing the console, so I can for example play looping music file while the project is running? Also it would be great if I could play other sounds on top of it, for example when you press enter it will plays a sound without stopping the music.

  2. How do I add the wav file so it compiles as a release?

EDIT

I know about the SND_ASYNC thing but I do not know how to use it, I can't seem to use it without the thing not compiling.. does anyone have an example of a code using SND_ASYNC?

EDIT 2

So I have this working now.... using the

PlaySound(TEXT("mysound.wav"), NULL, SND_FILENAME | SND_ASYNC);

Now I am wondering how I can get 1 or more sounds to play at once, for if I call PlaySound() twice with that flag it will stop the 1st one and play the 2nd.. Is there a way to play 2 sounds at once?


Solution

  • How can I play sounds without freezing the console?

    If you Google for PlaySound this is the first result:

    fdwSound

    ...

    SND_ASYNC 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.

    You should familiarise yourself with search engines and what they are capable of.

    How do I add the wav file so it compiles as a release?

    You need to link winmm.lib in both Release and Debug configurations. Alternatively, add

    #pragma comment(lib, "winmm.lib")
    

    to the top of your source code.