Example 8: DirectSound PCM and directsoundpcm

Source: Internet
Author: User

Example 8: DirectSound PCM and directsoundpcm
This document records the techniques used by DirectSound to play audio. DirectSound is the most common Audio Playback Technology in Windows. Currently, most audio playback applications use DirectSound. This article records an example of using DirectSound to play PCM.
Note: A dear friend has reminded me that DirectSound is planned to be replaced by XAudio2. Later, I found that this was the case. Therefore, in the next update, consider adding XAudio2 to play PCM. This article still records the DirectSound veteran ".



DirectSound introduction DirectSound is one of the components of DirectX developed by Microsoft. It can be recorded on Windows operating systems and waveform sound (waveform sound ). Currently, DirectSound is a mature API that provides many useful features, such as the ability to play multi-channel sound at a high resolution.
DirectSound3D (DS3D) was first published in 1993 with DirectX 3. DirectSound and DirectSound3D (DS3D) after DirectX 8 are collectively called DirectX Audio.


DirectSound has the following objects:

Object

Quantity

Function

Main Interface

Device

Each application has only one device object.

Used to manage devices and create secondary buffers

IDirectSound8

Secondary Buffer

Each sound corresponds to a secondary buffer.

Used to manage a static or dynamic sound stream, and then mixing in the main buffer zone

IDirectSoundBuffer8,

IDirectSound3DBuffer8,

Idirectsoundpolicy8

Primary buffer zone

An application has only one primary buffer.

Mixing the data in the secondary buffer and controlling 3D parameters.

IDirectSoundBuffer,

IDirectSound3DListener8



DirectSound audio playback process

To use DirectSound to play audio, follow these steps:

1. Initialization
1) Create an IDirectSound8 interface object
2) Set collaboration level
3) create a primary buffer object
4) create a secondary buffer object
5) create a notification object
6) set the notification location

7) start playing

2. Loop playback
1) Data is filled into the secondary buffer.

2) wait until the playback is complete

The following describes the process in detail.


1. Initialization
1) Create an IDirectSound8 interface object

You can use the DirectSoundCreate8 () method to create a device object. This object usually represents the default playing device. The DirectSoundCreate8 () function is defined as follows.
HRESULT DirectSoundCreate8( LPCGUID lpcGuidDevice, LPDIRECTSOUND8 * ppDS8, LPUNKNOWN pUnkOuter)

The parameters are described as follows:
LpcGuidDevice: GUID of the device object to be created. You can specify NULL to indicate the default playback device.
PpDS8: Address of the returned IDirectSound8 object.
PUnkOuter: It must be set to NULL.
For example, the following code creates an IDirectSound8 interface object.
IDirectSound8 *m_pDS=NULL;DirectSoundCreate8(NULL,&m_pDS,NULL);

2) Set collaboration level
Windows is a multi-task environment where multiple applications access devices at the same time. By using the collaboration level, DirectSound ensures that applications are not accessed by other devices. Each DirectSound application has a collaboration level, which determines the hardware access permission.
After creating a device object, you must use SetCooperativeLevel () of IDirectSound8 to set the cooperation permission. Otherwise, you will not be able to hear the sound. SetCooperativeLevel () is defined as follows:
HRESULT SetCooperativeLevel( HWND hwnd, DWORD dwLevel)

The parameters are described as follows:
Hwnd: application window handle.
DwLevel: the following levels are supported.
DSSCL_EXCLUSIVE: same role as DSSCL_PRIORITY.
DSSCL_NORMAL: the normal coordination level sign. Other programs can share the sound card device for playing.
DSSCL_PRIORITY: Set the sound card device to exclusive to the current program.
DSSCL_WRITEPRIMAR: The primary buffer zone can be written. At this time, the secondary buffer zone cannot be played, that is, the data in the secondary buffer zone cannot be sent to the sound mixer and then output to the primary buffer zone. This is the most comprehensive way to control sound playback.


3) create a primary buffer object
You can use CreateSoundBuffer () of IDirectSound8 to create a primary buffer object for the IDirectSoundBuffer interface. CreateSoundBuffer () is defined as follows.
HRESULT CreateSoundBuffer( LPCDSBUFFERDESC pcDSBufferDesc, LPDIRECTSOUNDBUFFER * ppDSBuffer, LPUNKNOWN pUnkOuter)

The parameters are described as follows:
PcDSBufferDesc: the address of the DSBUFFERDESC struct that describes the sound buffer.
PpDSBuffer: the address of the object of the returned IDirectSoundBuffer interface.
PUnkOuter: It must be set to NULL.
A structure DSBUFFERDESC describing sound buffering is involved. The structure is defined as follows:
typedef struct _DSBUFFERDESC{    DWORD           dwSize;    DWORD           dwFlags;    DWORD           dwBufferBytes;    DWORD           dwReserved;    LPWAVEFORMATEX  lpwfxFormat;} DSBUFFERDESC

Briefly explain the meanings of the variables:
DwSize: the size of the struct. This value must be initialized.
DwFlags: Set the audio cache attributes. There are many options, which can be used in combination and will not be listed one by one. For detailed parameters, see the documentation.
DwBufferBytes: the buffer size.
DwReserved: Reserved parameter. It is useless for the moment.
LpwfxFormat: pointer to a WAVE format file header.
After DSBUFFERDESC is set, you can use CreateSoundBuffer () to create the primary buffer. The sample code is as follows:
DSBUFFERDESC dsbd;memset(&dsbd,0,sizeof(dsbd));dsbd.dwSize=sizeof(dsbd);dsbd.dwFlags=DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLPOSITIONNOTIFY |DSBCAPS_GETCURRENTPOSITION2;dsbd.dwBufferBytes=MAX_AUDIO_BUF*BUFFERNOTIFYSIZE; //WAVE Headerdsbd.lpwfxFormat=(WAVEFORMATEX*)malloc(sizeof(WAVEFORMATEX));dsbd.lpwfxFormat->wFormatTag=WAVE_FORMAT_PCM;   /* format type */(dsbd.lpwfxFormat)->nChannels=channels;          /* number of channels (i.e. mono, stereo...) */(dsbd.lpwfxFormat)->nSamplesPerSec=sample_rate;     /* sample rate */(dsbd.lpwfxFormat)->nAvgBytesPerSec=sample_rate*(bits_per_sample/8)*channels; /* for buffer estimation */(dsbd.lpwfxFormat)->nBlockAlign=(bits_per_sample/8)*channels;        /* block size of data */(dsbd.lpwfxFormat)->wBitsPerSample=bits_per_sample;     /* number of bits per sample of mono data */(dsbd.lpwfxFormat)->cbSize=0;//Creates a sound buffer object to manage audio samples. HRESULT hr1;if( FAILED(m_pDS->CreateSoundBuffer(&dsbd,&m_pDSBuffer,NULL))){   return FALSE;}


4) create a secondary buffer object
You can use QueryInterface () of IDirectSoundBuffer to obtain an object of the IDirectSoundBuffer8 interface. The GUID of IDirectSoundBuffer8 is IID_IDirectSoundBuffer8. The sample code is as follows.
IDirectSoundBuffer *m_pDSBuffer=NULL;IDirectSoundBuffer8 *m_pDSBuffer8=NULL;...if( FAILED(m_pDSBuffer->QueryInterface(IID_IDirectSoundBuffer8,(LPVOID*)&m_pDSBuffer8))){return FALSE ;}


5) create a notification object
Use QueryInterface () of IDirectSoundBuffer8 to obtain an idirectsoundpolicy8 interface object. The GUID of IDirectSoundBuffer8 is IID_IDirectSoundNotify. The sample code is as follows.
IDirectSoundBuffer8 *m_pDSBuffer8=NULL;IDirectSoundNotify8 *m_pDSNotify=NULL;…if(FAILED(m_pDSBuffer8->QueryInterface(IID_IDirectSoundNotify,(LPVOID*)&m_pDSNotify))){return FALSE ;}


The purpose of the notification object is summarized in one sentence: After the data in the DirectSound buffer is played, the system is notified that new data should be filled.


6) set the notification location
You can use setnotifposipositions () of idirectsoundpolicy8 to set the notification location. Setnotifpositions () is defined as follows.
HRESULT SetNotificationPositions(         DWORD dwPositionNotifies,         LPCDSBPOSITIONNOTIFY pcPositionNotifies)

The parameter description is as follows.
DwPositionNotifies: Number of dsbpositionpolicy struct. Contains the location of several notifications.
PcPositionNotifies: pointer to the dsbpositionpolicy struct array.
Here, a struct dsbpositionpolicy describes the location of the notification. Dsbpositionpolicy is defined as follows.
typedef struct DSBPOSITIONNOTIFY {    DWORD dwOffset;    HANDLE hEventNotify;} DSBPOSITIONNOTIFY;

Its member meanings are as follows.
DwOffset: the trigger position of the notification event (offset from the starting position of the buffer ).
Heventpolicy: handle of the event to be triggered.


7) start playing
You can use SetCurrentPosition () of IDirectSoundBuffer8 to set the playback position. SetCurrentPosition () is defined as follows:
HRESULT SetCurrentPosition(         DWORD dwNewPosition)

DwNewPosition is the offset between the playback point and the first byte in the buffer zone.
You can use Play () of IDirectSoundBuffer8 to start playing audio data. Play () is defined as follows.
HRESULT Play(         DWORD dwReserved1,         DWORD dwPriority,         DWORD dwFlags)

Parameter description:
DwReserved1: Reserved parameter, which must be 0.
DwPriority: priority. Generally, you can set it to 0.
DwFlags: flag. Currently, DSBPLAY_LOOPING is common. When playing the video to the end of the buffer zone, play the video again from the beginning of the buffer zone.


2. Loop playback
1) Data is filled into the secondary buffer.

Use Lock () to Lock the buffer before filling data in the secondary buffer. Then, you can use fread (), memcpy (), and other methods to fill the PCM audio sample data into the buffer zone. After the data is filled, use Unlock () to cancel the buffer lock.
The Lock () function is defined as follows.
HRESULT Lock(         DWORD dwOffset,         DWORD dwBytes,         LPVOID * ppvAudioPtr1,         LPDWORD  pdwAudioBytes1,         LPVOID * ppvAudioPtr2,         LPDWORD pdwAudioBytes2,         DWORD dwFlags)

The parameter description is as follows.
DwOffset: the offset between the locked memory and the first address of the buffer.
DwBytes: the size of the locked cache.
PpvAudioPtr1: The obtained pointer to the cached data.
PdwAudioBytes1: size of the retrieved cache data.
PpvAudioPtr2: not used, set to NULL.
PdwAudioBytes2: it is not used and is set to 0.
DwFlags: no research at the moment.


The UnLock () function is defined as follows.
HRESULT Unlock(         LPVOID pvAudioPtr1,         DWORD dwAudioBytes1,         LPVOID pvAudioPtr2,         DWORD dwAudioBytes2)

The parameter description is as follows.
PvAudioPtr1: pointer to cached data obtained through Lock.
DwAudioBytes1: the volume of data written.
PvAudioPtr2: not used.

DwAudioBytes2: not used.

2) wait until the playback is complete

Based on the previously configured Notification Mechanism, use WaitForMultipleObjects () to wait for the data in the buffer zone to finish playing and then enter the next loop.


Audio playback process summary

Shows the process for DirectSound to play PCM audio data.

 

The relationships between several struct are shown in.
 




Code

Paste the source code.

/*** The Simplest example of DirectSound playing Audio (DirectSound playing PCM) * Simplest Audio Play DirectSound (DirectSound play PCM) ** leixiao Li Lei Xiaohua * leixiaohua1020@126.com * China Media University/Digital TV Technology * Communication University of China/Digital TV Technology * http://blog.csdn.net/leixiaohua1020 ** this program uses DirectSound to play PCM audio sample data. * Is the simplest tutorial for playing audio in DirectSound. ** Function call procedure: ** [initialization] * DirectSoundCreate8 (): Create a DirectSound object. * SetCooperativeLevel (): sets the collaboration permission, otherwise there is no sound. * IDirectSound8-> CreateSoundBuffer (): Creates a primary buffer object. * IDirectSoundBuffer-> QueryInterface (IID_IDirectSoundBuffer8 ..): * creates a secondary buffer object to store the audio data file to be played. * IDirectSoundBuffer8-> QueryInterface (IID_IDirectSoundNotify ..): * Create a notification object to notify the application that the specified playback position has reached. * Idirectsoundpolicy8-> setnotifposipositions (): sets the notification location. * IDirectSoundBuffer8-> SetCurrentPosition (): sets the start point of playback. * IDirectSoundBuffer8-> Play (): start playing. ** [Loop playback data] * IDirectSoundBuffer8-> Lock (): Lock the secondary buffer and prepare to write data. * Fread (): reads data. * IDirectSoundBuffer8-> Unlock (): Unlock the secondary buffer. * WaitForMultipleObjects (): Wait for the notification that "the playing position has reached. ** This software plays PCM raw audio data using DirectSound. * It's the simplest tutorial about DirectSound. ** The process is shown as follows: ** [Init] * DirectSoundCreate8 (): Init DirectSound object. * SetCooperativeLevel (): Must set, or we won't hear sound. * IDirectSound8-> CreateSoundBuffer (): Create primary sound buffer. * IDirectSoundBuffer-> QueryInterface (IID_IDirectSoundBuffer8 ..): * C Reate secondary sound buffer. * IDirectSoundBuffer8-> QueryInterface (IID_IDirectSoundNotify ..): * Create Notification object. * idirectsoundpolicy8-> setnotifposipositions (): * Set Notification Positions. * IDirectSoundBuffer8-> SetCurrentPosition (): Set position to start. * IDirectSoundBuffer8-> Play (): Begin to play. ** [Loop to play data] * IDirectSoundBuffer8-> Lock (): Lock secondary buffer. * fr Ead (): get PCM data. * IDirectSoundBuffer8-> Unlock (): UnLock secondary buffer. * WaitForMultipleObjects (): Wait for communications. */# include <stdio. h> # include <stdlib. h> # include <windows. h> # include <dsound. h> # define MAX_AUDIO_BUF 4 # define bufferpolicysize 192000 int sample_rate = 44100; // PCM sample rateint channels = 2; // PCM channel numberint bits_per_sample = 16; // bits per sampleBOOL main (int argc, ch Ar * argv []) {int I; FILE * fp; if (fp = fopen (".. /NocturneNo2inEflat_44.1k_s16le.pcm "," rb ") = NULL) {printf (" cannot open this file \ n "); return-1;} IDirectSound8 * m_tp= NULL; IDirectSoundBuffer8 * m_pDSBuffer8 = NULL; // used to manage sound buffers. IDirectSoundBuffer * m_pDSBuffer = NULL; idirectsoundpolicy8 * m_pdsnoloud = NULL; dsbpositionpolicy m_pDSPosNotify [MAX_AUDIO_BUF]; HANDLE m_event [MAX_AUDIO_BUF]; SetConsole Title (TEXT ("Simplest Audio Play DirectSound"); // Console Title // Init DirectSoundif (FAILED (DirectSoundCreate8 (NULL, & m_tp, NULL) return FALSE; if (FAILED (m_pDS-> SetCooperativeLevel (FindWindow (NULL, TEXT ("Simplest Audio Play DirectSound"), DSSCL_NORMAL) return FALSE; DSBUFFERDESC dsbd; memset (& dsbd, 0, sizeof (dsbd); dsbd. dwSize = sizeof (dsbd); dsbd. dwFlags = DSBCAPS_GLOBALFOCUS | dsbcaps_ctrlpositionpolicy | DS BCAPS_GETCURRENTPOSITION2; dsbd. dwBufferBytes = MAX_AUDIO_BUF * bufferpolicysize; // WAVE Headerdsbd. lpwfxFormat = (WAVEFORMATEX *) malloc (sizeof (WAVEFORMATEX); dsbd. lpwfxFormat-> wFormatTag = WAVE_FORMAT_PCM;/* format type */(dsbd. lpwfxFormat)-> nChannels = channels;/* number of channels (I. e. mono, stereo ...) */(dsbd. lpwfxFormat)-> nSamplesPerSec = sample_rate;/* sample rate */(dsbd. lpwfxFormat)-> nAvgBytesPerSe C = sample_rate * (bits_per_sample/8) * channels;/* for buffer estimation */(dsbd. lpwfxFormat)-> nBlockAlign = (bits_per_sample/8) * channels;/* block size of data */(dsbd. lpwfxFormat)-> wBitsPerSample = bits_per_sample;/* number of bits per sample of mono data */(dsbd. lpwfxFormat)-> cbSize = 0; // Creates a sound buffer object to manage audio samples. HRESULT hr1; if (FAILED (m_pDS-> CreateSoundBuffer (& dsbd, & m_pDSB Uffer, NULL) {return FALSE;} if (FAILED (m_pDSBuffer-> QueryInterface (IID_IDirectSoundBuffer8, (LPVOID *) & m_pDSBuffer8) {return FALSE ;} // Get idirectsoundpolicy8if (FAILED (m_pDSBuffer8-> QueryInterface (response, (LPVOID *) & m_pdsnooid) {return FALSE ;}for (I = 0; I <MAX_AUDIO_BUF; I ++) {m_pDSPosNotify [I]. dwOffset = I * bufferpolicysize; m_event [I] =: CreateEvent (NULL, false, false, NULL); m_pDSPosNotify [I]. hEventNotify = m_event [I];} m_pDSNotify-> seticationposipositions (optional, m_pDSPosNotify); m_pDSNotify-> Release (); // Start PlayingBOOL isPlaying = TRUE; LPVOID buf = NULL; DWORD buf_len = 0; DWORD res = WAIT_OBJECT_0; DWORD offset = bufferpolicysize; m_pDSBuffer8-> SetCurrentPosition (0); m_pDSBuffer8-> Play (0, 0, callback); // Loopwhile (isPlaying) {if (res> = WAIT_OBJECT_0) & (res <= WAIT_OBJECT_0 + 3) {m_pDSBuf Fer8-> Lock (offset, bufferpolicysize, & buf, & buf_len, NULL, NULL, 0); if (fread (buf, 1, buf_len, fp )! = Buf_len) {// File End // Loop: fseek (fp, 0, SEEK_SET); fread (buf, 1, buf_len, fp); // Close: // isPlaying = 0;} m_pDSBuffer8-> Unlock (buf, buf_len, NULL, 0); offset + = buf_len; offset % = (bufferpolicysize * MAX_AUDIO_BUF ); printf ("this is % 7d of buffer \ n", offset);} res = WaitForMultipleObjects (MAX_AUDIO_BUF, m_event, FALSE, INFINITE);} return 0 ;}


Running result

After the code is run, a "console" dialog box is displayed, as shown in. At the same time, the audio device can hear the playing sound.



 
Download

The code is in "Simplest Media Play"


SourceForge project: https://sourceforge.net/projects/simplestmediaplay/

Http://download.csdn.net/detail/leixiaohua1020/8054395 (CSDN)


The above project contains the use of various APIs (Direct3D, OpenGL, GDI, DirectSound, SDL2) to play multimedia examples. The audio input is PCM sampling data. Output to the sound card of the system. The video input is YUV/RGB pixel data. Output to a display window for playing.
The code of this project allows beginners to quickly learn how to use these APIs to play videos and audios.
The following sub-projects are included:
Simplest_audio_play_directsound: Use DirectSound to play PCM audio sample data.
Simplest_audio_play_sdl2: Use SDL2 to play PCM audio sample data.
Simplest_video_play_direct3d: Use the Direct3D Surface to play RGB/YUV video pixel data.
Simplest_video_play_direct3d_texture: Use Direct3D Texture to play RGB video pixel data.
Simplest_video_play_gdi: Use GDI to play RGB/YUV video pixel data.
Simplest_video_play_opengl: uses OpenGL to play pixel data of RGB/YUV videos.
Simplest_video_play_opengl_texture: use OpenGL Texture to play the YUV video pixel data.
Simplest_video_play_sdl2: Use SDL2 to play RGB/YUV video pixel data.




Question 200: Which audio player has the best sound quality?

Hello!

Which audio player has the best sound quality?

A: It is recommended to [pause and listen ];

Quiet listening is a completely free music playing software. It combines playback, sound effects, conversion, lyrics, and other functions. When playing a song, you can also automatically download and synchronously display the lyrics. The interface is beautiful, easy to operate, and powerful !!!
Www.ttplayer.com
Qianqian Forum: bbs.qianqian.com/index.php
Thousands of music online: www.qianqian.com/index.html

The new audio engine is independently developed by. It supports DirectSound, Kernel Streaming, ASIO audio stream output, 32-bit audio mixing, and AddIn extension technology, it has the advantages of low resource occupation, high operation efficiency, and strong scalability.

Supports audio formats such as MP/mp3PRO, AAC/AAC +, M4A/MP4, WMA, APE, MPC, OGG, WAVE, CD, FLAC, RM, TTA, AIFF, and AU. MOD and MIDI music, supports CUE audio track index files and converts all formats to WAVE, MP3, APE, and WMA formats. The AddIn plug-in based on the COM interface can support playback and conversion of more formats.

Supports sampling frequency conversion (SSRC) and multiple bit output modes, playback gain, 10-band balancer, multi-level Dolby surround, fade-in and fade-out sound effects, compatible with and can activate multiple Winamp2 sound plug-ins at the same time.

Supports ID3v1/v2, WMA, RM, APE, and Vorbis labels. You can modify tags in batches and rename files with tags.

You can synchronize the scrolling display and drag of the lyrics to locate the playback. You can also download and edit the lyrics.

Supports searching multiple playlists and audio files, supports multiple visual effects, and uses ZIP compressed skins in XML format, it also provides functions such as magnetic window, translucent/fade-in/fade-out window, window shadow, taskbar icon, custom shortcut keys, information scrolling, and menu function prompts.

Is a completely free music playing software that combines multiple functions such as playback, sound effects, conversion, and lyrics. Its small, exquisite, simple to operate, and powerful features are favored by users. It has been rated by netizens as one of the top ten excellent software in China and has become the most popular music playing software in China.
The new audio engine is independently developed by. It supports advanced audio stream output modes such as DirectSound, Kernel Streaming, and ASIO, 64-bit audio mixing, and AddIn plug-in Extension Technologies, it features low resource usage, high operation efficiency, and strong scalability.
Static audios support almost all common audio formats, audio formats include MP/mp3PRO, AAC/AAC +, M4A/MP4, WMA, APE, MPC, OGG, WAVE, CD, FLAC, RM, TTA, AIFF, and AU. MOD and MIDI music, as well as audio streams in a variety of video files, such as AVI, VCD, and DVD. It also supports CUE audio track index files.
Simple and Convenient operations allow easy conversion between multiple audio formats, including all the above formats (and audio streams in CD or DVD) to WAVE, MP3, APE ,...... remaining full text>

Strong Noise with a burst Pattern During directsound playback

How can I use static buffer for real-time reception and playback? buffer should be used for loop playback and "Event Notification" should be set to dynamically load the data to be played.
Doc.51windows.net/..ay.htm

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.