Use directsound (3) in Delphi: play the first wave file

Source: Internet
Author: User
After creating an idirectsound8 object, you must first set the collaboration priority through its setcooperativelevel () method;
This is a required step because other applications may use this device (Sound Card) at the same time.
Function setcooperativelevel (hwnd: hwnd; // window handle dwlevel: DWORD // collaboration priority): hresult; stdcall; // collaboration priority option dsscl_normal = 1; // common; the primary buffer cannot be modified, compressed, or set. Other applications that use this device dsscl_priority = 2; // priority; can be set but cannot be directly written to the primary buffer, the secondary buffer uses dsscl_exclusive = 3; // exclusive; out-of-date, same as dsscl_prioritydsscl_writeprimary = 4; // top-level; it must be directly written to the primary buffer and cannot be used; this requires you to write your own sound mixing program. Maybe only the designer can do this.
Then, use the idirectsound8.createsoundbuffer () method to create a buffer. This process is mainly to fill in the tdsbufferdesc structure;
When entering the tdsbufferdesc structure, the twaveformatex structure pointer is also required. This twaveformatex structure will be read directly from the wave file.

Unless the priority is set to dsscl_writeprimary, the program should have at least one buffer zone (which will automatically create the primary buffer zone at the same time), and the sound of the buffer zone will eventually be output through the primary buffer mixing.

The buffer zone is divided into static and streaming buffers:
Stream buffer is suitable for playing large audio files. The principle is to write and change the playback speed (the program is very troublesome to write );
The static buffer can be set to the desired size at a time, so that only one write is enough. This simple method is used in the following example.

Function createsoundbuffer (const pcdsbufferdesc: tdsbufferdesc; // describe the Buffer structure out ppdsbuffer: buffers; // buffer object punkouter: iunknown // unused, nil): hresult; stdcall; // error code tdsbufferdesc = packed record dwsize: DWORD; // structure size (in bytes). To use this structure, assign dwflags: DWORD to it; // function ID dwbufferbytes: DWORD; // buffer size dwreserved: DWORD; // unused, must be 0 lpwfxformat: pwaveformatex; // pointer guid3dalgorithm: tguid of the twaveformatex structure; // guid constant for 3D algorithms; the version after dx7 is available. The current structure has this field end more than the previous tdsbufferdesc1. // tdsbufferdesc. dwflags: dsbcaps_primarybuffer = $00000001; // use the primary buffer. The default value is dsbcaps_static = $00000002; // static buffer. If possible, the buffer is created on the sound card; the default value is to create a streaming buffer dsbcaps_lochardware =$ 00000004; // force the use of a hard buffer dsbcaps_locsoftware =$ 00000008; // force the use of a soft buffer dsbcaps_ctrl3d =l00000010; // The buffer zone has the 3D control capability dsbcaps_ctrlfrequency = $00000020; // the buffer zone has the frequency control capability dsbcaps_ctrlpan = $00000040; // the buffer zone has the phase control capability dsbcaps_ctrlvolume = $00000080; // The buffer zone has the volume control capability dsbcaps_ctrlpositionnotify = $00000100; // the buffer zone has the location notification capability dsbcaps_ctrlfx = $00000200; // the buffer zone supports the special effect dsbcaps_stickyfocus = $00004000; // when the program switches to another program that does not use directsound, you can continue playing the video; otherwise, dsbcaps_globalfocus = $00008000 will be muted; // even if the program switches to another program that uses directsound, this buffer is still available, unless other programs prioritize dsbcaps_getcurrentposition2 = $00010000; // enable getcurrentposition to obtain a more precise playback position dsbcaps_mute3datmaxdistance = $00020000; // The maximum attenuation distance, only applicable to soft buffer dsbcaps_locdefer = $00040000; // determine whether to use hard buffer or soft buffer dsbcaps_trueplayposition = $00080000 for directsound automatic latency; // force getcurrentposition to return the actual playback position, valid only for Versions later than Vista
Before writing data to the buffer, use the idirectsoundbuffer. Lock () method to lock the memory (Disable Windows to automatically manage this memory ).

Lock () returns the write pointer and data size through its VaR parameter (the buffer here, especially the buffer provided by the device, is not too large, so the size is not too random ).

Lock () returns two write pointers and two data sizes (one pair). When writing data to the end of the buffer cannot be written, it is necessary to go back and write data from the beginning. In this case, the second pointer and size are required.
This dual-pointer program is also a bit bypassed. Fortunately, this example only uses one pointer for the time being.

Lock () has two lock ID constants. In this example, dsblock_entirebuffer is used to lock the entire buffer, so that the first two parameters are not considered for the moment.

Unlock after writing.

Function lock (dwoffset: DWORD; // The offset dwbytes: DWORD at the start of lock; // number of bytes to lock ppvaudioptr1: ppointer; // output the first memory pointer pdwaudiobytes1: pdword; // output the number of locked bytes ppvaudioptr2: ppointer; // output the second memory pointer pdwaudiobytes2: pdword; // output the number of locked bytes dwflags: DWORD // lock control flag): hresult; stdcall; // error code // lock. dwflagsdsblock_fromwritecursor = $00000001; // lock from the write position. The parameter dwoffset will be ignored dsblock_entirebuffer = $00000002; // lock the entire buffer, and the parameter dwbytes will be ignored. // function unlock (pvaudioptr1: pointer; // The first lock offset dwaudiobytes1: DWORD; // The number of bytes to be unlocked pvaudioptr2: pointer; // The second lock offset dwaudiobytes2: DWORD // number of bytes to be unlocked): hresult; stdcall; // error code
After writing, you can use idirectsoundbuffer. Play () and stop () to control the playback:
Function play (dwreserved1: DWORD; // not used, 0 dwpriority: DWORD; // not used, 0 dwflags: DWORD // playback control flag; if you only play the video once, you can directly give 0): hresult; stdcall; // play. duration = $00000001; // cyclically play dsbplay_lochardware = $00000002; // play only the hard buffer sound dsbplay_locsoftware = $00000004; // play only the soft buffer sound dsbplay_terminateby_time = $00000008; // do not learn dsbplay_terminateby_distance = $00000010; // do not learn dsbplay_terminateby_priority = $00000020; // do not learn yet // function stop: hresult; stdcall; // it is more appropriate to pause
Before learning the program I wrote down, I thought about whether to use dsutil. Pas, which was previously written by my predecessors. But I gave up on it for various reasons, but I still wanted to understand it thoroughly.

The program uses two previously written functions:
Http://www.cnblogs.com/del/archive/2009/11/06/1597735.html
Http://www.cnblogs.com/del/archive/2009/11/06/1597735.html

The test program only uses three buttons and prepares a test file (C: \ temp \ test.wav ).

Unit unit1; interfaceuses windows, messages, sysutils, variants, classes, graphics, controls, forms, dialogs, stdctrls; Type tform1 = Class (tform) button1: tbutton; button2: tbutton; button3: tbutton; Procedure upload (Sender: tobject); Procedure formdestroy (Sender: tobject); Procedure button1click (Sender: tobject); Procedure button2click (Sender: tobject ); procedure button3click (Sender: tobject); end; var form1: tform1; implementation {$ R *. DFM} uses directsound, mmsystem; const wavpath = 'C: \ temp \ test.wav '; // The Wave Used for testing. Ensure that the file exists and pay attention to the path permission, and it can only be a PCM wave file var mydsound: idirectsound8; Buf: idirectsoundbuffer; // buffer object {function for retrieving the twaveformatex structure from the wave file} function getwavefmt (filepath: string; vaR FMT: twaveformatex): Boolean; var hfile: hmmio; ckiriff, ckifmt: tmmckinfo; begin result: = false; hfile: = mmioopen (pchar (filepath), nil, mmio_read ); if hfile = 0 Then exit; zeromemory (@ ckiriff, sizeof (tmmckinfo); zeromemory (@ ckifmt, sizeof (tmmckinfo); zeromemory (@ FMT, sizeof (bytes )); ckifmt. ckid: = mmiostringtofourcc ('fmt', 0); mmiodescend (hfile, @ ckiriff, nil, mmio_findriff); If (ckiriff. ckid = fourcc_riff) and (ckiriff. fcctype = mmiostringtofourcc ('wave ', 0) and (mmiodescend (hfile, @ ckifmt, @ ckiriff, timeout) = mmsyserr_noerror) then result: = (mmioread (hfile, @ FMT, ckifmt. cksize) = ckifmt. cksize); mmioclose (hfile, 0); end; {function for obtaining waveform data from the wave file} function getwavedata (filepath: string; var stream: tmemorystream): Boolean; vaR hfile: hmmio; ckiriff, ckidata: tmmckinfo; begin result: = false; hfile: = mmioopen (pchar (filepath), nil, mmio_read); If hfile = 0 Then exit; zeromemory (@ ckiriff, sizeof (tmmckinfo); zeromemory (@ ckidata, sizeof (tmmckinfo); ckidata. ckid: = mmiostringtofourcc ('data', 0); mmiodescend (hfile, @ ckiriff, nil, mmio_findriff); If (ckiriff. ckid = fourcc_riff) and (ckiriff. fcctype = mmiostringtofourcc ('wave ', 0) and (mmiodescend (hfile, @ ckidata, @ ckiriff, mmio_findchunk) = mmsyserr_noerror) then begin stream. size: = ckidata. cksize; Result: = (mmioread (hfile, stream. memory, ckidata. cksize) = ckidata. cksize); end; mmioclose (hfile, 0); end; {program initialization} procedure tform1.formcreate (Sender: tobject); begin button1.caption: = 'establish and play'; button2.caption: = 'replay play'; button3.caption: = 'stopped'; button2.enabled: = false; button3.enabled: = false; system. reportmemoryleaksonshutdown: = true; // Let the program automatically report Memory leakage end; {main program} procedure tform1.button1click (Sender: tobject); var bufdesc: tdsbufferdesc; // construct the wavformat: twaveformatex required for creating the buffer; // The wavdata: tmemorystream structure extracted from the wave; // The waveform data extracted from the wave P1: pointer; // The write pointer N1: DWORD obtained from the buffer; // The data size to be written to the buffer. Begin {reads the format and waveform data from the wave file} if not getwavefmt (wavpath, wavformat) then exit; wavdata: = tmemorystream. create; if not getwavedata (wavpath, wavdata) then begin wavdata. free; exit; end; {create a device object and set the writing priority} directsoundcreate8 (nil, mydsound, nil); mydsound. setcooperativelevel (self. handle, dsscl_normal); {fill the structure required to establish the buffer} zeromemory (@ bufdesc, sizeof (tdsbufferdesc); bufdesc. dwsize: = sizeof (tdsbufferdesc); bufdesc. dwflags: = dsbcaps_static; // specify the static buffer bufdesc. dwbufferbytes: = wavdata. size; // data size bufdesc. lpwfxformat: = @ wavformat; // data format // bufdesc. guid3dalgorithm: = ds3dalg_default; // This does not require {buffer creation} mydsound. createsoundbuffer (bufdesc, Buf, nil); {lock the buffer memory to get the write address and size} Buf. lock (0, 0, @ P1, @ N1, nil, nil, dsblock_entirebuffer); {write} wavdata. position: = 0; copymemory (P1, wavdata. memory, N1); wavdata. free; {unlock} Buf. unlock (P1, N1, nil, 0); {play} Buf. play (0, 0, 0); button1.enabled: = false; button2.enabled: = true; button3.enabled: = true; end; {loop playback} procedure tform1.button2click (Sender: tobject ); begin Buf. play (0, 0, dsbplay_looping); end; {pause playing} procedure tform1.button3click (Sender: tobject); begin Buf. stop; end; // Release Interface, otherwise there will be Memory leakage (because the lifecycle of this buffer may be longer than the application); and the release order is also very important procedure tform1.formdestroy (Sender: tobject); begin Buf: = nil; mydsound: = nil; end.

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.