Method for playing sound in VC ++ by Li canwei

Source: Internet
Author: User
Method for playing sound in VC ++ Author: Li can Wei Release Date: 2001/05/16
 
Abstr:
This article discusses several different methods for playing audio files in VC ++, and provides specific implementation examples.
Keywords: audio file audio device playback multimedia

Body:  


How to play a sound in VC ++

Sound is an important part of multimedia. Adding sound to an application can make the interface more friendly. In VC ++, you can use different methods to achieve sound playback based on different application requirements.

I. Simple Method for playing audio files
A set of functions related to audio devices are provided in the multimedia dynamic Connection Library of VC ++. These functions can be used to conveniently play the sound. The simplest way to play a sound is to directly call the sound playing function bool sndplaysound (lpcstr lpszsound, uint fusound) provided in VC ++; or bool playsound (lpcstr lpszsound, hmodule hmod, DWORD fusound), where the parameter lpszsound needs to be played. the path and file name of the wav file. hmod is null here, And fusound is the symbol of the playing sound. For details, see the help in VC ++. For example, to play C:/sound/music.wav, you can use sndplaysound ("C: // sound // music.wav", snd_async); or playsound ("C: // sound // music.wav ", null, snd_async | snd_nodefault audio streams if the music.wav file is not found, the default sound of the system is played in the first format, and the default sound of the system is not played in the second format.

2. Add the sound file to the program
In VC ++ programming, various standard resources such as bitmaps, menus, and dialogs can be used. At the same time, VC ++ also allows users to customize resources. Therefore, we can add audio files as user-defined resources to program resource files and generate EXE files after compilation connection to achieve no. audio Playback of wav files.
To play the audio file of a resource, you must first add the audio file to be played in the Resource Manager (the implementation process is not complex, but is not described here ). Assume that the generated audio file resource identifier is idr_wave1. During playback, you only need to call the following statement:
Playsound (makeintresource (idr_wave1), afxgetresourcehandle (), snd_async | snd_resource | snd_nodefault | snd_loop );
The makeintresource () macro converts an integer Resource Identifier to a string. The afxgetresourcehandle () function returns the module handle containing the resource,
Snd_resource is a required identifier.
The second method for playing audio files of resources is to read the resources into the memory and play back the data as memory. Perform the following steps:
1. Obtain the module handle containing resources:
Hmodule hmod = afxgetresourcehandle ();
2. retrieve resource block information:
Hrsrc hsndresource = findresource (hmod, makeintresource (idr_wave1), _ T ("wave "));
3. Load and lock resource data:
Hglobal hglobalmem = loadresource (hmod, hsndresource );
Lpctstr lpmemsound = (lpcstr) lockresource (hglobalmem );
4. Play the audio file:
Sndplaysound (lpmemsound, snd_memory ));
5. Release the resource handle:
Freeresource (hglobalmem );

Iii. advanced methods for playing audio files
In VC ++, a set of functions are provided to directly operate audio devices and multimedia files. Using these functions, You can flexibly Process audio files.
First, we will introduce several data structures to be used. The waveformatex structure defines the format of the wave audio data file. The wavehdr structure defines the waveform audio buffer. The read data must be filled in the buffer before the audio device can play the video. The waveoutcaps Structure describes the performance of audio devices. The mmckinfo structure contains the information of a block in the riff file. For more information, see help in VC ++.
The following is a simple program flow diagram and a list of program source code, which can be directly used in the VC ++ environment:

The source program list is as follows:
Lpstr szfilename; // audio file name
Mmckinfo mmckinfoparent;
Mmckinfo mmckinfosubchunk;
DWORD dwfmtsize;
Hmmio m_hmmio; // audio file handle
DWORD m_wavelong;
Hpstr lpdata; // audio data
Handle m_hdata;
Handle m_hformat;
Waveformatex * lpformat;
DWORD m_dwdataoffset;
DWORD m_dwdatasize;
Wavehdr pwaveouthdr;
Waveoutcaps pwoc;
Hwaveout;
// Open the waveform file
If (! (M_hmmio = mmioopen (szfilename, null, mmio_read | mmio_allocbuf )))
{
// File open Error
Error ("failed to open the file."); // error handling function
Return false;
}
// Check whether the opened file is a sound file
Mmckinfoparent. fcctype = mmiofourcc ('w', 'A', 'V', 'E ');
If (mmiodescend (m_hmmio, (lpmmckinfo) & mmckinfoparent, null, mmio_findriff ))
{
// Not wave file and quit
}
// Find the 'fmt' Block
Mmckinfosubchunk. ckid = mmiofourcc ('F', 'M','t ','');
If (mmiodescend (m_hmmio, & mmckinfosubchunk, & mmckinfoparent, mmio_findchunk ))
{
// Can't find 'fmt' chunk
}
// Obtain the size of the 'fmt' block and apply for memory
Dwfmtsize = mmckinfosubchunk. cksize;
M_hformat = localalloc (lmem_moveable, loword (dwfmtsize ));
If (! M_hformat)
{
// Failed alloc memory
}
Lpformat = (waveformatex *) locallock (m_hformat );
If (! Lpformat)
{
// Failed to lock the memory
}
If (unsigned long) mmioread (m_hmmio, (hpstr) lpformat, dwfmtsize )! = Dwfmtsize)
{
// Failed to read format chunk
}
// Exit the FMT Block
Mmioascend (m_hmmio, & mmckinfosubchunk, 0 );
// Search for 'data' Blocks
Mmckinfosubchunk. ckid = mmiofourcc ('D', 'A', 't', 'A ');
If (mmiodescend (m_hmmio, & mmckinfosubchunk, & mmckinfoparent, mmio_findchunk ))
{
// Can't find 'data' chunk
}
// Obtain the size of the 'data' Block
M_dwdatasize = mmckinfosubchunk. cksize;
M_dwdataoffset = mmckinfosubchunk. dwdataoffset;
If (m_dwdatasize = 0l)
{
// No data in the 'data' chunk
}
// Allocate memory for Audio Data
Lpdata = new char [m_dwdatasize];
If (! Lpdata)
{
// Faile
}
If (mmioseek (m_hmmio, soundoffset, seek_set) <0)
{
// Failed to read the data chunk
}
M_wavelong = mmioread (m_hmmio, lpdata, soundlong );
If (m_wavelong <0)
{
// Failed to read the data chunk
}
// Check the audio device and return the performance of the audio output device.
If (waveoutgetdevcaps (wave_mapper, & pwoc, sizeof (waveoutcaps ))! = 0)
{
// Unable to allocate or lock memory
}
// Check whether the audio output device can play the specified audio file
If (waveoutopen (& hwaveout, devsnum, lpformat, null, null, callback_null )! = 0)
{
// Failed to open the wave out devices
}
// Prepare the data to be played
Pwaveouthdr. lpdata = (hpstr) lpdata;
Pwaveouthdr. dwbufferlength = m_wavelong;
Pwaveouthdr. dwflags = 0;
If (waveoutprepareheader (hwaveout, & pwaveouthdr, sizeof (wavehdr ))! = 0)
{
// Failed to prepare the wave data buffer
}
// Play the audio data file
If (waveoutwrite (hwaveout, & pwaveouthdr, sizeof (wavehdr ))! = 0)
{
// Failed to write the wave data buffer
}
// Disable the audio output device and release the memory
Waveoutreset (hwaveout );
Waveoutclose (hwaveout );
Localunlock (m_hformat );
Localfree (m_hformat );
Delete [] lpdata;
Note: 1) the declaration of the above audio device and sound file operation function is included in mmsystem. the # include "mmsystem. H "statement to add the header file. At the same time, you must add dynamic connection import and export to winmm during compilation. lib. The specific implementation method is to select Settings from the project menu of developer studio, and then add winmm to the object/library modules control on the Link tab. lib. 2) You can specify different data in pwaveouthdr. lpdata to play the sound at any specified position in the audio data file. 3) All the above programs have passed the debugging in VC ++ 6.0, and the handling of errors and exceptions is omitted in this article, which must be added to practical applications.
Iv. Conclusion
In VC ++, you can use different methods to play audio files as needed. Simple Applications can directly call the sound playback function. The second method adds sound to an executable file as a resource. If you want to process audio data before playing the video, you can use the third method.

Bibliography:
1. American Paul Perry Chen xiangqun translated Multimedia Development Guide by Tsinghua University Press
2. Us Peter Norton, Rob McGregor sun fengying translated "MFC development Windows95/NT4 application program" by Tsinghua University Press 1998
3. Zhou jingli multimedia sound card technology and application, Electronic Industry Press 1998

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.