Search code examples
cvisual-c++playsound

Visual C++ or C play sounds


I'm developping an easy game written in C (Visual C++) and I want to know if there is a way to play sounds, thanks (I'm using Visual Studio)


Solution

  • Take a look at the PlaySound() function.

    If you call PlaySound() with the SND_ASYNC flag, the function returns immediately after beginning the sound.

    For example:

    #include <windows.h>
    #include <mmsystem.h>
    
    PlaySound(L"test.wav", NULL, SND_ASYNC | SND_FILENAME);
    

    You'll also have to add Winmm.lib in your project settings.


    Here's a quick example that should work:

    #pragma once
    
    #include "stdafx.h"
    #include <windows.h>
    #include <mmsystem.h>
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        if(!PlaySound(L"test.wav", NULL, SND_ASYNC | SND_FILENAME))
            printf("error\n");
        else
            printf("ok\n");
    
        getch();
        return 0;
    }
    

    and in stdafx.h:

    #pragma once
    
    #include <iostream>
    #include <tchar.h>
    #include <conio.h>