Audio Manager API Sample Reference for audio tone generation
Please follow the below steps to play a tone in an active tone generator stream.
1. Get the AudioFactory instance
auto &audioFactory = audioFactory::getInstance();
2. Get the AudioManager object and check for audio subsystem Readiness
std::promise<ServiceStatus> prom{};
audioManager = audioFactory.getAudioManager([&prom](ServiceStatus serviceStatus) {
prom.set_value(serviceStatus);
});
if (!audioManager) {
std::cout << "Failed to get AudioManager object" << std::endl;
return;
}
ServiceStatus managerStatus = audioManager->getServiceStatus();
if (managerStatus != ServiceStatus::SERVICE_AVAILABLE) {
std::cout << "\nAudio subsystem is not ready, Please wait ..." << std::endl;
managerStatus = prom.get_future().get();
}
if (managerStatus == ServiceStatus::SERVICE_AVAILABLE) {
std::cout << "Audio Subsytem is Ready << std::endl;
} else {
std::cout << "ERROR - Unable to initialize audio subsystem" << std::endl;
return;
}
3. Create an audio Stream (to be associated with tone generator)
void createStreamCallback(std::shared_ptr<IAudioStream> &stream, ErrorCode error) {
if (error != ErrorCode::SUCCESS) {
std::cout << "createStream() failed with error" << static_cast<int>(error) << std::endl;
return;
}
std::cout << "createStream() succeeded." << std::endl;
audioToneGeneratorStream = std::dynamic_pointer_cast<IAudioToneGeneratorStream>(stream);
}
config.type = telux::audio::StreamType::TONE_GENERATOR;
config.sampleRate = 48000;
config.format = AudioFormat::PCM_16BIT_SIGNED;
config.channelTypeMask = ChannelType::LEFT;
config.deviceTypes.emplace_back(DeviceType::DEVICE_TYPE_SPEAKER);
status = audioManager->createStream(config, createStreamCallback);
4. Play tone on a sink device
void playToneCallback(ErrorCode error)
{
if (error != ErrorCode::SUCCESS) {
std::cout << "playTone() failed with error" << static_cast<int>(error) << std::endl;
return;
}
std::cout << "playTone() succeeded." << std::endl;
}
status = audioToneGeneratorStream->playTone(freq, duration, gain, playToneCallback);
5. Optionally, you can stop the tone being played before the specified duration elapses
void stopToneCallback(ErrorCode error)
{
if (error != ErrorCode::SUCCESS) {
std::cout << "stopTone() failed with error " << static_cast<int>(error) << std::endl;
return;
}
std::cout << "stopTone() succeeded." << std::endl;
}
status = audioToneGeneratorStream->stopTone(stopToneCallback);
6. Delete the audio stream associated with the Tone Generator session
void deleteStreamCallback(ErrorCode error) {
if (error != ErrorCode::SUCCESS) {
std::cout << "deleteStream() failed with error" << static_cast<int>(error) << std::endl;
return;
}
std::cout << "deleteStream() succeeded." << std::endl;
audioToneGeneratorStream.reset();
}
status = audioManager->deleteStream(
std::dynamic_pointer_cast<IAudioStream>(audioToneGeneratorStream), deleteStreamCallback);