Link to home
Start Free TrialLog in
Avatar of bradsoblesky
bradsoblesky

asked on

MIDI sound

How can I play MIDI sounds? This is very important and urgent. Thanks.
ASKER CERTIFIED SOLUTION
Avatar of olgat
olgat

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of olgat
olgat

I'm sorry for so messy answer, I'll try it once more :-)



MIDI.CPP
/*==========================================================================
 *  
 *  Copyright (C) 1995-1997 Microsoft Corporation. All Rights Reserved.  
 *  
 *  File: midi.cpp  
 *  
 ***************************************************************************
 /  // Includes....
 #include "windows.h"
 #include "midi.h"
 #include "stdio.h"  

// Externals.... extern HWNDg_hWnd;  
//------------------------------------------------------------------
//  
// Function: PlayMidi()
//
// Purpose: Plays a midi file
//
//------------------------------------------------------------------  
BOOL PlayMidi(char *sFileName)
{    
      char buf[256];      
      sprintf(buf, "open %s type sequencer alias MUSIC", sFileName);
      
      if (mciSendString("close all", NULL, 0, NULL) != 0)    
      {
            return(FALSE);    
      }
            
      if (mciSendString(buf, NULL, 0, NULL) != 0)
      {
            return(FALSE);
      }
      
      if (mciSendString("play MUSIC from 0", NULL, 0, g_hWnd) != 0)
      {
            return(FALSE);    
      }
      
      // Yahoo!
      return TRUE;
}  

//------------------------------------------------------------------
//  
// Function: PauseMidi()
//
// Purpose: Pauses midi file
//
//------------------------------------------------------------------  
BOOL PauseMidi()
{    
      // Pause if we're not already paused...    
      if (mciSendString("stop MUSIC", NULL, 0, NULL) != 0)    
      {
            return(FALSE);    
      }
      
      // Yahoo!    
      return TRUE;
}  

//------------------------------------------------------------------
//  
// Function: ResumeMidi()
//
// Purpose: Resumes playing of a midi file
//
//------------------------------------------------------------------
BOOL ResumeMidi()
{    
      // Resume midi    
      if (mciSendString("play MUSIC notify", NULL, 0, g_hWnd) != 0)
      {
            return(FALSE);
      }
      
      // Yahoo!
      
      return TRUE;
}

//------------------------------------------------------------------
//  
// Function: StopMidi
//
// Purpose: Stops a midi file playing
//
//------------------------------------------------------------------  
BOOL StopMidi()
{    
      if (mciSendString("close all", NULL, 0, NULL) != 0)
      {
            return(FALSE);
      }
      
      // Yahoo!
      return TRUE;
}

//------------------------------------------------------------------
//  
// Function: ReplayMidi()
//
// Purpose: Replays a midi file
//
//------------------------------------------------------------------  
BOOL ReplayMidi()
{    
      // Replay midi
      if (mciSendString("play MUSIC from 0 notify", NULL, 0, g_hWnd) != 0)
      {
            return(FALSE);
      }
      
      // Yahoo!
      return TRUE;
}  
Avatar of bradsoblesky

ASKER

ok, give me some time to try it out and i'll accept your answer. Thanks.
i'm having some trouble here, fill me in on the details i'm slow. can i just include this Midi.cpp and make the call to it to play? do i need the full path of the file?
Hi:
Yes, you can include this midi.cpp file to your project as is,
and yes, you need the full path of the MIDI file being played.
If you need a working sample, let me know.
please the smallest example would help. Have some compile problems.
Hi:
Here is a sample.
6 files -
midi.cpp, midiDlg.cpp, midi.rc,
midi.h, midiDlg.h, resource.h

Things to pay attention -
1. incude "mmsystem.h"
2. link with winmm.lib
3. there is a bug in the sample, it plays only files from the same directory where your .exe resides. I^m sorry, I have no time just now to fix it
:-(

********************************
// 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");
}


************************************
//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

************************************// 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_)

*************************************
//{{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

that's cool, thank you so much.