Windows Basics-Play audio using XAudio2 (essentially WASAPI)

Source: Internet
Author: User

For common audio playback, using XAudio2 is sufficient. time is to kill a pig knife, funny is that I became a pig

Back in Windows Vista, m$ introduced the new audio architecture UAA, where CoreAudio took over Dsound, wavexxx, and mediafundation, through Core audio APIs, The audio performance of Windows can be comparable to MacOS X (Manual laughter).

Universal Audio Architecture (UAA)

CoreAudio belongs to the UAA, only a series of audio processing at the user layer, and the system core is only responsible for submitting buffered data to the audio driver.

Before the advent of UAA, the program ran like this:

Now the program runs in UAA like this:

Wasapi and XAudio2Star of Core Audio APIs: WASAPI

The Wasapi can provide very low audio latency without the SRC direct output.
To reduce audio latency, more like AISO,WASAPI is used in two ways: Push, a buffer queue, often used for audio playback. One is an event (which must be exclusive), provided by the hardware clock or audio API to drive you to submit the audio data (it's so complicated, really useless, what to do with the cache), so you can significantly reduce the audio delay, as if the DMA will skip (not verified), for the game, Real-time mixing and other real-time requirements for more demanding occasions.
On Fidelity, Wasapi was blown marvellous by Foobar2000 users. And it is at best less a src process, as for the difference between the two modes, entertainment on the line. What human voice sweet sound field wide burr less and so the mysterious flow, have this kung fu or spend some money, you need better equipment.
To the user, Wasapi is really strong in the APO (audio processing Objects), based on the sound of this technology is theoretically compatible with all devices (perhaps the problem of the DSP algorithm, I encountered a sampling rate limit, once more than 96000Hz failure).

XAudio2 from DirectX:

XAudio2 is a call to Wasapi in the version of Windows that uses UAA.
About Fidelity, your program runs on XP Dsound, the system using UAA directly corresponds to WASAPI, can also skip SRC, and audio low latency performance is enough to meet the needs of music games and the like.
The original xaudio was used for Xbox,xaudio2 to start with the tri-Red Machine and Vista and above both. In today's unification environment (using the Windows native API), playing audio is either WASAPI or XAudio2. The biggest advantage of using XAudio2 is that it is easier to program audio than WASAPI, while playing audio when you just keep submitting the data of the audio buffer gradually compose the queue just fine, the disadvantage is ... For the general development of audio playback, there is no drawback at the moment, except for the ultra-low latency that even the DMA can skip (in exchange for higher hardware resource occupancy and almost no experience boost). The use of system resources is also delayed and WASAPI see what is the difference. Only from audio playback, the individual recommends using XAudio2 rather than WASAPI.
Its version is now 2.9 in WINDOWS10 and continues to be used by developers in WINRT and UWP technologies.

gossip is easy, which gives you code:

This is a simple example of what I wrote when I was doing speech synthesis, representing the most commonly used audio playback scenarios, all of which are:
PS: The synthesized samplerate is lower than the output frequency of the sound card work, must pass the software src (Sample rate Converter), otherwise come out is the quick release effect, the default parameter when creating the source is to open its built-in SRC.

Required header files and static libraries#include <Windows.h>#include <XAudio2.h>#pragma comment (lib, "Xaudio2.lib")/* #include "SpeechSynthesis.h" This is Speechsynthesis's header file */speechsynthesis Syth (Sc_mandarin);Speech synthesizer-Simplified Chinese to putonghua waveformatex format = Syth. wfx;Waveform format IXAudio2 * Xaudioengine =NULL;IXAduio2 Audio Engine Ixaudio2masteringvoice * Pmaster =NULL;Sound Manager ixaudio2sourcevoice * Psource =NULL;Audio source Xaudio2_buffer sbuffer = {};Sound source buffer Xaudio2_voice_state pState = {};Buffer stateLists the initialization and uninstallation separately, which can be added to your constructor-destructorBOOL Init () {XAudio2 Initialize CoInitializeEx (NULL, coinit_multithreaded);if (FAILED (Xaudio2create (&xaudioengine)))ReturnFALSE;if (FAILED (Xaudioengine->createmasteringvoice (&pmaster)))ReturnFALSE;if (FAILED (Xaudioengine->createsourcevoice (&psource, &format)))ReturnFALSE;ReturnTRUE;}void UnInit () {xaudioengine->release (); CoUninitialize ();}Functions of speech synthesis and audio renderingBOOL vocalize (wchar_t * srcsentence) {psource->start ();Turn on the audio source Sbuffer. Paudiodata = Syth. Synthesize (srcsentence);Synthetic Audio Sbuffer. Audiobytes = Syth. pcm_data. Size ();Load audio buffers at onceif (FAILED (Psource->submitsourcebuffer (&sbuffer)))Return0;Loading audioWait for the play to complete or interruptFor (Psource->getstate (&pstate); pState1); Psource->stop (); //off the source psource->flushsourcebuffers (); //buffer empty (optional) return TRUE;} int Main (int argc, char *argv[]) { Init (); Vocalize (L "This is a Test speech"); Vocalize (L "excerpt from the" Let Me in your Heart free "); Vocalize (L "she instantly took off her calm mask, and the sun-like smile filled her eyes. She cast a real look at me, and her voice left me at a loss to be touched. She was sometimes quiet and supple like a girl next door, sometimes a pair of black and big eyes flashing the light of the elves. In her music, she is one in the Prairie Blue Clear sky free soaring eagle, the release of their broad vision and vast ideals. Her heart is lonely and confused, wandering and melancholy, but still stubbornly guarding the freedom of the spirit, but also learned in the real life silently bear. "); UnInit (); return 0;}         

The visible process is very simple:
After initialization can be Psource->start () can also first configure the Sbuffer and Submitsourcebuffer, the three order is very free, the common sense of the line; for Sbuffer, it is only necessary to let it know the audio buffer pointer and buffer length, As for the loop parameters, as the name implies, there is no need to verbose.
It then polls the audio buffer state to prevent the buffer from being loaded.
When you stop playing, you can clear the buffer queue of the source, in some cases you need to interrupt and play other sounds, you need to use flushsourcebuffers (), otherwise the effect is to queue the sound all finished.

The next play repeats the above actions directly.

Tips

As mentioned earlier, when the source is initialized, the default is to open SRC, that is, automatic resampling to ensure the correct playback speed.
When creating a sound source, there is an int flag called: XAUDIO2_VOICE_NOSRC. You can modify the third parameter at initialization time to achieve no src:

CreateSourceVoice(&pSource, &format,XAUDIO2_VOICE_NOSRC);

As the name implies, when you ensure that the audio sampling rate and device output settings are consistent, you can skip SRC, the bit-perfect you want is not castrated because of DX, and the code is not wasapi so jumbled.

Windows Basics-Play audio using XAudio2 (essentially WASAPI)

Related Article

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.