The audio workgroup is a set of APIs that help the system identify critical audio threads within an app through tagging. By providing critical audio threads and workgroup runtime information, the system can improve the stability of audio thread execution.
The following examples are code snippets. For the complete sample, click the link at the bottom right of the example.
For audio playback apps, you need to first create an audio workgroup, and then periodically notify the system of the workgroup runtime information. When the work is complete, clean up the audio workgroup.
Before calling any API of OH_AudioWorkgroup, you must use OH_AudioManager_GetAudioResourceManager to obtain an OH_AudioResourceManager instance.
#include <ohaudio/native_audio_resource_manager.h>
// ...
OH_AudioResourceManager *resMgr;
// ...
OH_AudioManager_GetAudioResourceManager(&resMgr); Call OH_AudioResourceManager_CreateWorkgroup to create an audio workgroup, and then call OH_AudioWorkgroup_AddCurrentThread to add key threads to the workgroup.
#include <chrono>
// ...
int32_t g_tokenId;
OH_AudioWorkgroup *grp = nullptr;
// ...
OH_AudioResourceManager_CreateWorkgroup(resMgr, "workgroup", &grp);
OH_AudioWorkgroup_AddCurrentThread(grp, &g_tokenId); When an audio workgroup begins a cycle of work, you can notify the system of the task's start time and expected end time. When the workgroup finishes its work for the current cycle, notify the system that the task has ended.
constexpr static uint64_t intervalMs = 20;
bool threadShouldRun = true;
while (threadShouldRun) {
auto now = std::chrono::system_clock::now().time_since_epoch();
auto startTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(now).count();
OH_AudioWorkgroup_Start(grp, startTimeMs, startTimeMs + intervalMs);
// This is sample logic. In actual development, control the thread running cycle based on business requirements.
threadShouldRun = false;
// Process audio data.
OH_AudioWorkgroup_Stop(grp);
}