Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:78 Xiaozhi esp32 AudioService

From Leeroopedia
Knowledge Sources
Domains Audio_Processing, Real_Time_Systems, Embedded_Systems
Last Updated 2026-10-17 00:00 GMT

Overview

Concrete tool for managing the bidirectional audio pipeline provided by the XiaoZhi firmware, coordinating audio input (microphone capture), Opus encode/decode, audio output (speaker playback), and wake word detection through bounded queues and dedicated FreeRTOS tasks.

Description

AudioService is the central audio coordinator. It owns:

  • Audio codec: codec_ (I2S microphone/speaker interface)
  • Audio engine: audio_engine_ (AFE/Lite for AEC, VAD, wake word)
  • Opus encoder/decoder: opus_encoder_, opus_decoder_
  • Resamplers: input_resampler_ (codec→16kHz), output_resampler_ (decoder→speaker)
  • Bounded queues: audio_decode_queue_ (20), audio_send_queue_ (40), audio_encode_queue_ (2), audio_playback_queue_ (2)
  • Three FreeRTOS tasks: AudioInputTask, AudioOutputTask, OpusCodecTask
  • Event group: AS_EVENT_WAKE_WORD_RUNNING, AS_EVENT_AUDIO_PROCESSOR_RUNNING, AS_EVENT_AUDIO_TESTING_RUNNING, AS_EVENT_AUDIO_INPUT_STOP_REQUEST

The service provides high-level control methods: EnableWakeWordDetection(), EnableVoiceProcessing(), EnableAudioTesting(), PlaySound(), ResetDecoder(), and queue accessors PushPacketToDecodeQueue() / PopPacketFromSendQueue().

Usage

Reference this implementation when:

  • Tracing audio data flow through the pipeline
  • Understanding queue capacities and overflow behavior
  • Adding a new audio processing mode (testing, debugging)
  • Implementing playback drain detection
  • Configuring Opus encode/decode parameters

Code Reference

Source Location

  • Repository: XiaoZhi ESP32
  • Files: main/audio/audio_service.h, main/audio/audio_service.cc

Signature

class AudioService {
public:
    AudioService();
    ~AudioService();

    void Initialize(AudioCodec* codec);
    void Start();
    void Stop();
    void EncodeWakeWord();
    std::unique_ptr<AudioStreamPacket> PopWakeWordPacket();
    const std::string& GetLastWakeWord() const;
    std::vector<std::string> GetWakeWords() const;
    bool IsVoiceDetected() const;
    bool IsIdle();
    bool IsPlaybackIdle();
    bool IsWakeWordRunning() const;
    bool IsAudioProcessorRunning() const;
    bool IsAfeWakeWord();

    void EnableWakeWordDetection(bool enable);
    void ReleaseWakeWordResources();
    void EnableVoiceProcessing(bool enable);
    void EnableAudioTesting(bool enable);
    void EnableDeviceAec(bool enable);

    void SetCallbacks(AudioServiceCallbacks& callbacks);
    bool PushPacketToDecodeQueue(std::unique_ptr<AudioStreamPacket> packet, bool wait = false);
    std::unique_ptr<AudioStreamPacket> PopPacketFromSendQueue();
    void PlaySound(const std::string_view& sound);
    bool ReadAudioData(std::vector<int16_t>& data, int sample_rate, int samples);
    void ResetDecoder();
    void SetModelsList(srmodel_list_t* models_list);

private:
    void AudioInputTask();
    void AudioOutputTask();
    void OpusCodecTask();
    void PushTaskToEncodeQueue(AudioTaskType type, std::vector<int16_t>&& pcm);
    bool InitializeAudioEngine();
    void SetDecodeSampleRate(int sample_rate, int frame_duration);
    bool IsPlaybackDrainedLocked() const;
    bool MarkPlaybackDrainedLocked();
    // ...
};

struct AudioServiceCallbacks {
    std::function<void(void)> on_send_queue_available;
    std::function<void(const std::string&)> on_wake_word_detected;
    std::function<void(bool)> on_vad_change;
    std::function<void(void)> on_audio_testing_queue_full;
    std::function<void(void)> on_playback_drained;
    std::function<void(uint32_t, uint32_t)> on_playback_progress;
};

Import

#include "audio_service.h"

I/O Contract

Inputs

Name Type Required Description
codec AudioCodec* Yes I2S audio codec from the board
callbacks AudioServiceCallbacks& Event callbacks for wake word, VAD, send queue, playback drain
packet std::unique_ptr<AudioStreamPacket> Incoming Opus packet for decode queue
models_list srmodel_list_t* Speech recognition models for wake word

Outputs

Name Type Description
Initialize() Encoder/decoder/resamplers created; audio engine initialized; tasks ready to start
Start() AudioInputTask, AudioOutputTask, OpusCodecTask created and started
PopPacketFromSendQueue() Encoded Opus packet ready for network send (or nullptr if empty)
on_send_queue_available Fires when send queue has packets (sets MAIN_EVENT_SEND_AUDIO)
on_playback_drained Fires when decode+playback fully drained (sets MAIN_EVENT_PLAYBACK_DRAINED)

Usage Examples

Initialization and Callback Wiring

auto& audio = Application::GetInstance().GetAudioService();

// Initialize with board's codec
audio.Initialize(board.GetAudioCodec());

// Wire callbacks
AudioServiceCallbacks callbacks;
callbacks.on_send_queue_available = []() { /* signal main loop */ };
callbacks.on_wake_word_detected = [](const std::string& word) { /* signal main loop */ };
callbacks.on_playback_drained = []() { /* signal main loop */ };
audio.SetCallbacks(callbacks);

// Start audio tasks
audio.Start();

Sending Audio to the Server

// In the main event loop, on MAIN_EVENT_SEND_AUDIO:
while (auto packet = audio_service_.PopPacketFromSendQueue()) {
    if (!protocol_->SendAudio(std::move(packet))) {
        break;  // send failed, stop draining
    }
}

Receiving Audio from the Server

// Register the incoming audio callback
protocol_->OnIncomingAudio([this](std::unique_ptr<AudioStreamPacket> packet) {
    if (GetDeviceState() == kDeviceStateSpeaking) {
        audio_service_.PushPacketToDecodeQueue(std::move(packet));
    }
});

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment