Include sound

Experts out there again,
Could you all give me some help. This one is really simple. May I know how to include a sound in my C++ program that keeps on looping. Also, may I know how to include a button for user to click so that the sound will stop playing. Futhermore, may I know how to include a sound that plays only once.

Currently I am using Visual C++ on Windows 98.

I will increase the points if answers are excellent. Please help a beginer in C++.

Thanks,
hongjun
LVL 33
hongjunAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

olgatCommented:
Hi:
Here is a little sample for playing MIDI sounds. Let me know if you want any other type of sound *WAV, etc.).
The sample is an MFC one.
Happy coding!

There are 9 files in the sample:
midi.cpp
midiDlg.cpp
midiPlayer.cpp
stdAfx.cpp

midi.h
midiDlg.h
midiPlayer.h
stdafx.h

midi.rc
resource.h

************************************
// midi.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "midi.h"
#include "midiDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMidiApp

BEGIN_MESSAGE_MAP(CMidiApp, CWinApp)
      //{{AFX_MSG_MAP(CMidiApp)
            // NOTE - the ClassWizard will add and remove mapping macros here.
            //    DO NOT EDIT what you see in these blocks of generated code!
      //}}AFX_MSG
      ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMidiApp construction

CMidiApp::CMidiApp()
{
      // TODO: add construction code here,
      // Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CMidiApp object

CMidiApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CMidiApp initialization

BOOL CMidiApp::InitInstance()
{
      AfxEnableControlContainer();

      // Standard initialization
      // If you are not using these features and wish to reduce the size
      //  of your final executable, you should remove from the following
      //  the specific initialization routines you do not need.

#ifdef _AFXDLL
      Enable3dControls();                  // Call this when using MFC in a shared DLL
#else
      Enable3dControlsStatic();      // Call this when linking to MFC statically
#endif

      CMidiDlg dlg;
      m_pMainWnd = &dlg;
      int nResponse = dlg.DoModal();
      if (nResponse == IDOK)
      {
            // TODO: Place code here to handle when the dialog is
            //  dismissed with OK
      }
      else if (nResponse == IDCANCEL)
      {
            // TODO: Place code here to handle when the dialog is
            //  dismissed with Cancel
      }

      // Since the dialog has been closed, return FALSE so that we exit the
      //  application, rather than start the application's message pump.
      return FALSE;
}


************************************
// midiDlg.cpp : implementation file
//

#include "stdafx.h"
#include "midi.h"
#include "midiDlg.h"
#include "stdio.h"  
#include "mmsystem.h"
 

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMidiDlg dialog

CMidiDlg::CMidiDlg(CWnd* pParent /*=NULL*/)
      : CDialog(CMidiDlg::IDD, pParent)
{
      //{{AFX_DATA_INIT(CMidiDlg)
            // NOTE: the ClassWizard will add member initialization here
      //}}AFX_DATA_INIT
      // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
      m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMidiDlg::DoDataExchange(CDataExchange* pDX)
{
      CDialog::DoDataExchange(pDX);
      //{{AFX_DATA_MAP(CMidiDlg)
            // NOTE: the ClassWizard will add DDX and DDV calls here
      //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMidiDlg, CDialog)
      //{{AFX_MSG_MAP(CMidiDlg)
      ON_WM_PAINT()
      ON_WM_QUERYDRAGICON()
      ON_BN_CLICKED(IDC_PLAY, OnPlay)
      ON_BN_CLICKED(IDC_STOP, OnStop)
      ON_BN_CLICKED(IDC_PAUSE, OnPause)
      ON_BN_CLICKED(IDC_RESUME, OnResume)
      ON_BN_CLICKED(IDC_OPEN, OnOpen)
      ON_BN_CLICKED(IDC_REPLAY, OnReplay)
      //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMidiDlg message handlers

BOOL CMidiDlg::OnInitDialog()
{
      CDialog::OnInitDialog();

      // Set the icon for this dialog.  The framework does this automatically
      //  when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                  // Set big icon
      SetIcon(m_hIcon, FALSE);            // Set small icon
      
      // TODO: Add extra initialization here
      
      return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMidiDlg::OnPaint()
{
      if (IsIconic())
      {
            CPaintDC dc(this); // device context for painting

            SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

            // Center icon in client rectangle
            int cxIcon = GetSystemMetrics(SM_CXICON);
            int cyIcon = GetSystemMetrics(SM_CYICON);
            CRect rect;
            GetClientRect(&rect);
            int x = (rect.Width() - cxIcon + 1) / 2;
            int y = (rect.Height() - cyIcon + 1) / 2;

            // Draw the icon
            dc.DrawIcon(x, y, m_hIcon);
      }
      else
      {
            CDialog::OnPaint();
      }
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMidiDlg::OnQueryDragIcon()
{
      return (HCURSOR) m_hIcon;
}

//------------------------------------------------------------------
//  
// Function: PlayMidi()
//
// Purpose: Plays a midi file
//
//------------------------------------------------------------------  
void CMidiDlg::OnPlay()
{
      MCIERROR errCode;
      char buf[256];    
      char errText[256];      

      wsprintf(buf, "open %s type sequencer alias MUSIC", m_sFileName);
//      wsprintf(buf1, "open %s type sequencer alias MUSIC", "D:\\Samples\\ExEx\\midi\\Debug\\Rock.mid");
      
      if (mciSendString("close all", NULL, 0, NULL) != 0)      
      {
            MessageBox("couldn't close");
            return;      
      }

      errCode = mciSendString(buf, NULL, 0, NULL);
      if (errCode != 0)
      {
            mciGetErrorString(errCode, errText, 256);
            MessageBox(errText);
            return;      
      }

      if (mciSendString("play MUSIC from 0", NULL, 0, m_hWnd) != 0)
      {
            MessageBox("couldn't play");
            return;      
      }

}

//------------------------------------------------------------------
//  
// Function: StopMidi
//
// Purpose: Stops a midi file playing
//
//------------------------------------------------------------------  
void CMidiDlg::OnStop()
{
      if (mciSendString("close all", NULL, 0, NULL) != 0)
            MessageBox("couldn't close all");
}

//------------------------------------------------------------------
//  
// Function: PauseMidi()
//
// Purpose: Pauses midi file
//
//------------------------------------------------------------------  
void CMidiDlg::OnPause()
{
      // Pause if we're not already paused...      
      if (mciSendString("stop MUSIC", NULL, 0, NULL) != 0)      
            MessageBox("couldn't stop");
}

//------------------------------------------------------------------
//  
// Function: ResumeMidi()
//
// Purpose: Resumes playing of a midi file
//
//------------------------------------------------------------------
void CMidiDlg::OnResume()
{
      // Resume midi      
      if (mciSendString("play MUSIC notify", NULL, 0, m_hWnd) != 0)
            MessageBox("couldn't resume");
}

void CMidiDlg::OnOpen()
{
      static char szFilter[] = "midi (*.mid)||";
 
      CFileDialog Dlg(TRUE, "*.mid", 0,
                              OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
                              szFilter, AfxGetMainWnd());

      // Cancel or Escape
      if (Dlg.DoModal () != IDOK)
            return;

      m_sFileName = Dlg.GetPathName();
      
}

//------------------------------------------------------------------
//  
// Function: ReplayMidi()
//
// Purpose: Replays a midi file
//
//------------------------------------------------------------------  
void CMidiDlg::OnReplay()
{
      // Replay midi
      if (mciSendString("play MUSIC from 0 notify", NULL, 0, m_hWnd) != 0)
            MessageBox("couldn't replay");
}

************************************
// MidiPlayer.cpp: implementation of the CMidiPlayer class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "midi.h"
#include "MidiPlayer.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMidiPlayer::CMidiPlayer()
{

}

CMidiPlayer::~CMidiPlayer()
{

}

**************************************
// stdafx.cpp : source file that includes just the standard includes
//      midi.pch will be the pre-compiled header
//      stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"



************************************
// midi.h : main header file for the MIDI application
//

#if !defined(AFX_MIDI_H__840953C4_BABF_11D3_80C6_009027A3103C__INCLUDED_)
#define AFX_MIDI_H__840953C4_BABF_11D3_80C6_009027A3103C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#ifndef __AFXWIN_H__
      #error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"            // main symbols

/////////////////////////////////////////////////////////////////////////////
// CMidiApp:
// See midi.cpp for the implementation of this class
//

class CMidiApp : public CWinApp
{
public:
      CMidiApp();

// Overrides
      // ClassWizard generated virtual function overrides
      //{{AFX_VIRTUAL(CMidiApp)
      public:
      virtual BOOL InitInstance();
      //}}AFX_VIRTUAL

// Implementation

      //{{AFX_MSG(CMidiApp)
            // NOTE - the ClassWizard will add and remove member functions here.
            //    DO NOT EDIT what you see in these blocks of generated code !
      //}}AFX_MSG
      DECLARE_MESSAGE_MAP()
};


/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_MIDI_H__840953C4_BABF_11D3_80C6_009027A3103C__INCLUDED_)

***********************************
// midiDlg.h : header file
//

#if !defined(AFX_MIDIDLG_H__840953C6_BABF_11D3_80C6_009027A3103C__INCLUDED_)
#define AFX_MIDIDLG_H__840953C6_BABF_11D3_80C6_009027A3103C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

/////////////////////////////////////////////////////////////////////////////
// CMidiDlg dialog

class CMidiDlg : public CDialog
{
// Construction
public:
      CMidiDlg(CWnd* pParent = NULL);      // standard constructor

// Dialog Data
      //{{AFX_DATA(CMidiDlg)
      enum { IDD = IDD_MIDI_DIALOG };
            // NOTE: the ClassWizard will add data members here
      //}}AFX_DATA

      // ClassWizard generated virtual function overrides
      //{{AFX_VIRTUAL(CMidiDlg)
      protected:
      virtual void DoDataExchange(CDataExchange* pDX);      // DDX/DDV support
      //}}AFX_VIRTUAL

// Implementation
protected:
      HICON m_hIcon;

      // Generated message map functions
      //{{AFX_MSG(CMidiDlg)
      virtual BOOL OnInitDialog();
      afx_msg void OnPaint();
      afx_msg HCURSOR OnQueryDragIcon();
      afx_msg void OnPlay();
      afx_msg void OnStop();
      afx_msg void OnPause();
      afx_msg void OnResume();
      afx_msg void OnOpen();
      afx_msg void OnReplay();
      //}}AFX_MSG
      DECLARE_MESSAGE_MAP()

      CString m_sFileName;
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_MIDIDLG_H__840953C6_BABF_11D3_80C6_009027A3103C__INCLUDED_)

*************************************
// MidiPlayer.h: interface for the CMidiPlayer class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_MIDIPLAYER_H__840953CE_BABF_11D3_80C6_009027A3103C__INCLUDED_)
#define AFX_MIDIPLAYER_H__840953CE_BABF_11D3_80C6_009027A3103C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CMidiPlayer  
{
public:
      CMidiPlayer();
      virtual ~CMidiPlayer();

};

#endif // !defined(AFX_MIDIPLAYER_H__840953CE_BABF_11D3_80C6_009027A3103C__INCLUDED_)

*******************************
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by midi.rc
//
#define IDD_MIDI_DIALOG                 102
#define IDR_MAINFRAME                   128
#define IDC_PLAY                        1000
#define IDC_STOP                        1001
#define IDC_PAUSE                       1002
#define IDC_RESUME                      1003
#define IDC_OPEN                        1004
#define IDC_REPLAY                      1005

// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE        129
#define _APS_NEXT_COMMAND_VALUE         32771
#define _APS_NEXT_CONTROL_VALUE         1005
#define _APS_NEXT_SYMED_VALUE           101
#endif
#endif

*********************************
// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#if !defined(AFX_STDAFX_H__840953C8_BABF_11D3_80C6_009027A3103C__INCLUDED_)
#define AFX_STDAFX_H__840953C8_BABF_11D3_80C6_009027A3103C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define VC_EXTRALEAN            // Exclude rarely-used stuff from Windows headers

#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions
#include <afxdisp.h>        // MFC Automation classes
#include <afxdtctl.h>            // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>                  // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT


//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_STDAFX_H__840953C8_BABF_11D3_80C6_009027A3103C__INCLUDED_)

*******************************
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"

#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"

/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS

/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32

/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//

IDD_MIDI_DIALOG DIALOGEX 0, 0, 193, 42
STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_APPWINDOW
CAPTION "midi"
FONT 8, "MS Sans Serif"
BEGIN
    DEFPUSHBUTTON   "OK",IDOK,167,7,26,14
    PUSHBUTTON      "Play",IDC_PLAY,34,7,26,14
    PUSHBUTTON      "Stop",IDC_STOP,59,7,26,14
    PUSHBUTTON      "Pause",IDC_PAUSE,86,7,26,14
    PUSHBUTTON      "Resume",IDC_RESUME,114,7,26,14
    PUSHBUTTON      "Open",IDC_OPEN,7,7,26,14
    PUSHBUTTON      "Replay",IDC_REPLAY,139,7,26,14
END


#ifndef _MAC
/////////////////////////////////////////////////////////////////////////////
//
// Version
//

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,0,1
 PRODUCTVERSION 1,0,0,1
 FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
 FILEOS 0x4L
 FILETYPE 0x1L
 FILESUBTYPE 0x0L
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904B0"
        BEGIN
            VALUE "CompanyName", "\0"
            VALUE "FileDescription", "midi MFC Application\0"
            VALUE "FileVersion", "1, 0, 0, 1\0"
            VALUE "InternalName", "midi\0"
            VALUE "LegalCopyright", "Copyright (C) 1999\0"
            VALUE "LegalTrademarks", "\0"
            VALUE "OriginalFilename", "midi.EXE\0"
            VALUE "ProductName", "midi Application\0"
            VALUE "ProductVersion", "1, 0, 0, 1\0"
        END
    END
    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1200
    END
END

#endif    // !_MAC


/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//

#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO DISCARDABLE
BEGIN
    IDD_MIDI_DIALOG, DIALOG
    BEGIN
        LEFTMARGIN, 7
        TOPMARGIN, 7
        BOTTOMMARGIN, 35
    END
END
#endif    // APSTUDIO_INVOKED

#endif    // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////
// Unknown language: 0xD, 0x1 resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_HEB)
#ifdef _WIN32
LANGUAGE 0xD, 0x1
#pragma code_page(1255)
#endif //_WIN32

#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//

1 TEXTINCLUDE DISCARDABLE
BEGIN
    "resource.h\0"
END

2 TEXTINCLUDE DISCARDABLE
BEGIN
    "#include ""afxres.h""\r\n"
    "\0"
END

3 TEXTINCLUDE DISCARDABLE
BEGIN
    "#define _AFX_NO_SPLITTER_RESOURCES\r\n"
    "#define _AFX_NO_OLE_RESOURCES\r\n"
    "#define _AFX_NO_TRACKER_RESOURCES\r\n"
    "#define _AFX_NO_PROPERTY_RESOURCES\r\n"
    "\r\n"
    "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n"
    "#ifdef _WIN32\r\n"
    "LANGUAGE 9, 1\r\n"
    "#pragma code_page(1252)\r\n"
    "#endif //_WIN32\r\n"
    "#include ""res\\midi.rc2""  // non-Microsoft Visual C++ edited resources\r\n"
    "#include ""afxres.rc""         // Standard components\r\n"
    "#endif\r\n"
    "\0"
END

#endif    // APSTUDIO_INVOKED


/////////////////////////////////////////////////////////////////////////////
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDR_MAINFRAME           ICON    DISCARDABLE     "res\\midi.ico"
#endif    // Unknown language: 0xD, 0x1 resources
/////////////////////////////////////////////////////////////////////////////



#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
#define _AFX_NO_SPLITTER_RESOURCES
#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE 9, 1
#pragma code_page(1252)
#endif //_WIN32
#include "res\midi.rc2"  // non-Microsoft Visual C++ edited resources
#include "afxres.rc"         // Standard components
#endif

/////////////////////////////////////////////////////////////////////////////
#endif    // not APSTUDIO_INVOKED



0
hongjunAuthor Commented:
Sorry olgat,

I understand that your answer must be the correct one. However, I find difficulty in finding the source codes for each file especially midi.rc.

If you do not mind the trouble, could you send those files to my email account

asteroids_88@hotmail.com

I believe this will be of great help to me. By the way, I have increased the point for this question from 120 to 130 as an encouragement. I will however increase this if your codes are satisfactory and I might grade you a A because I can see that you are keen to help.

Hope to hear from you soon.

Thanks,
hongjun
0
gambisticsCommented:
I think if you want to play a sound you have it as a file. You can use this function to play a file:

PlaySound("C:\example.wav",NULL,SND_FILENAME|SND_LOOP|SND_ASYNC);

You can delete SND_LOOP if you don't want the sound to loop.
If you want to stop a sound you can call the same function:

PlaySound(NULL,NULL,NULL);
0
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

gambisticsCommented:
Sorry I forgot a thing. You have to include "mmsystem.h":

#include "mmsystem.h" and under the tab "Link" you have to specify "winmm.lib" at object/lib files
0
hongjunAuthor Commented:
What do you mean by
under the tab "Link" you have to specify "winmm.lib" at object/lib files
0
gambisticsCommented:
You have also to include the lib-file in your Project. To do so you have to open the Project/Settings, go to Link nd specify winmm.lib at object/lib files
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.