C++ Console : Sound Play

Console is not as boring as it looks right? So far we have seen that there is nothing that is not possible with console. Here we have yet another good thing that can be very interesting for console programmers and is very good for gaming projects.
Sound play in console is not very difficult. If code is arranged in specific manner then it's just to use the code and have fun. Please read these notes first:
  • link must have \\ between two folder names like "D:\\folder 1\\folder 2\\folder 3\\file.wav"
  • write filename correctly with it's extension .wav
  • audio files other then .wav are not supported by this
  • convert your files to .wav via convertor or online site like this: Convert Audio Online
Let's have a look at code:

 #include <Windows.h>  
 #pragma comment (lib,"winmm.lib")  
 void soundPlay(LPCWSTR link);  
 void soundStop();  
 UINT wDeviceID;  
 void main(){  
  LPCWSTR link = TEXT("D:\\tone.wav");  
  soundPlay(link);  
  Sleep(10000);  
  soundStop();  
  system("pause");  
 }  
 void soundPlay(LPCWSTR link)  
 {  
  soundStop();  
  DWORD dwReturn;  
  MCI_OPEN_PARMS mciOpenParms;  
  mciOpenParms.lpstrDeviceType = TEXT("waveaudio");  
  mciOpenParms.lpstrElementName = link;  
  dwReturn = mciSendCommand(NULL, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD)(LPVOID)&mciOpenParms);  
  wDeviceID = mciOpenParms.wDeviceID;  
  dwReturn = mciSendCommand(wDeviceID, MCI_PLAY, 0, NULL);  
 }  
 void soundStop()  
 {  
  mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);  
 }  
Copy code and run. The most important thing is the address of the file in line 8 of the code. Read these carefully to get to know this code:

Comments

Popular posts from this blog

C++ Console : Basic Graphic Techniques

C++ Console : Change Font Size

C++ Console : Color