# Speaker

How the Kode Dot sounds, and how your app plays a sound through its speaker.

## What it is

Inside the case there is a small speaker. Your app can play a
tone through it with `kode_audio_tone`, a WAV file with `kode_audio_play` or
its own samples with `kode_audio_play_samples`.

All the Kode Dot's sound, out through the speaker and in through the
[microphone](/device/microphone), goes through an audio codec, the **ES8311**.
The codec turns the samples your app sends into sound and digitises what the
microphone picks up. It works in mono, at 48 kHz and 16 bits.

![Animation. The Kode Dot standing, seen from the front, from its left and a little from below. High on the left edge, a grille of small holes with a label: speaker, it plays through this grille. The beep from this page's example plays and blue waves come out of the grille to the left. On the right are the call kode_audio_play_samples(), the 440 Hz tone, volume 60 and a bar from 0 to 300 ms that fills while it plays. Then the waves move away and it goes quiet. Label: the example's beep comes out of the grille, in slow motion.](/device/speaker/beep.webp)

## How it is connected

KodeOS runs the codec and the amplifier, so your app opens no bus and calls
the SDK instead. The P4 gives the codec its settings, such as the volume, over the
[shared I2C bus](/device/overview#how-it-is-connected) and sends it the sound
over I2S. Of the four I2S pins, GPIO38 carries the sound and the other three
are the clock, which the speaker and the microphone share. The codec passes the
sound to the amplifier, an NS4150B, and the amplifier drives the speaker.

![The ESP32-P4, which runs your code, reaches the audio codec, an ES8311, over two buses. One is the I2C bus at address 0x18, on GPIO4 and GPIO5, and the other is the I2S bus, on GPIO34, GPIO36, GPIO37 and GPIO38. The codec sends the sound to the amplifier, an NS4150B, and from there to the 8 ohm, 1 W speaker. Below, the ESP32-C5, the radio, switches the amplifier on with its GPIO4.](/device/speaker/connection.webp)

The amplifier is switched on by the C5, the radio chip. That is why the C5 has
to be running for anything to be heard, even if your app uses neither Wi-Fi nor
Bluetooth. If your app has the radio off, like the template with
`CONFIG_KODEOS_RADIO=n` in `sdkconfig.defaults`, KodeOS resets the C5 at
start-up and leaves it running for the amplifier. The full circuit is in the
[main board schematic](/hardware/main-board).

## Specifications

- **1 W**: The nominal power of the speaker, a YN1811-0801WD of 8 Ω. It resonates at about 1.3 kHz and below about 400 Hz it makes no sound.
- **Class D**: The amplifier, an NS4150B, is class D.
- **48 kHz, 16-bit, mono**: The sound format, with no conversion.
- **Volume from 0 to 100**: Set with `kode_audio_set` and `"volume"`. `"mute"` at 1 silences it and at 0 brings the sound back. The setting lasts until the next reset. 100 is the loudest the speaker takes without overheating, and it sits below the codec's full scale.
- **Tones from 400 to 3400 Hz**: `kode_audio_tone(hz, ms)` lasts up to 65535 ms. What you hear is the nearest of eight frequencies, from 1020 to 1957 Hz.
- **WAV from the microSD or the flash**: `kode_audio_play` reads a WAV from `sd/...` or from `flash/...`.
- **200 ms of sound held**: That is how much a stream buffers. `kode_audio_stream_open` opens the speaker for sound your app makes a piece at a time, `kode_audio_stream_write` sends each piece and `kode_audio_stream_close` closes it. It closes by itself after 10 s without a write.
- **Never at the same time as the microphone**: The speaker and the microphone do not work at the same time, as [Microphone](/device/microphone#gotchas) explains.

The calls are `kode_audio_tone`, `kode_audio_play_samples` and
`kode_audio_play`, in `kode.h`, and they return once the sound has ended. For
background playback and everything else, see
[the SDK API](/sdk/kode#api-the-standard-layer-audio).

## Gotchas

- **The calls return true and nothing is heard**: With `CONFIG_KODEOS_RADIO=n`, the amplifier takes about 1.5 s from the start of the app to come on, and whatever plays before that is lost. Wait a couple of seconds before the first sound.
- **Your tone has a different pitch from the one you asked for**: `kode_audio_tone` uses the nearest of its eight frequencies. For an exact pitch, generate the samples and play them with `kode_audio_play_samples`, as the example does.
- **kode_audio_play refuses your file**: It plays only 48 kHz, 16-bit, mono WAV, and `kode_error()` says what does not fit. Convert the file first.

## Apps that use it

- https://apps.kode.diy/app/b243504a-280d-4a65-bf86-0545d20b104c
- https://apps.kode.diy/app/27f0629d-bc04-4cfc-9109-eb696eaad5f5
- https://apps.kode.diy/app/4b9a0c02-1491-442a-a1ae-981b695542c5

## Example code

Run the program and you hear three notes, C, E and G, again every second until
you leave the app. Because the program builds the sound sample by sample, each
note sounds at its exact pitch.

```c
/* SPDX-License-Identifier: GPL-3.0-or-later */
/**
 * @file speaker_chime.c
 * @brief Plays three notes, C, E and G, through the speaker of the Kode Dot, over and over.
 *
 * It builds the chime sample by sample, so each note sounds at its exact
 * pitch, and plays it once a second until you leave the app.
 *
 * from Kode with love
 */
#include <math.h>
#include "kode.h"

#define CHIME_RATE_HZ  48000U       /**< Samples per second. */
#define CHIME_NOTE_N   7200U        /**< Samples in one note: 150 ms at 48 kHz. */
#define CHIME_NOTES    3U           /**< Notes in the chime. */
#define CHIME_PEAK     16000.0f     /**< Height of the wave, out of 32767. */
#define CHIME_PI       3.14159265f  /**< Pi, for the sine. */
#define CHIME_VOLUME   80U          /**< Speaker volume, from 0 to 100. */
#define CHIME_PAUSE_MS 1000U        /**< Silence between two chimes. */

/** @brief The chime, one sample per frame. */
static int16_t s_samples[CHIME_NOTES * CHIME_NOTE_N];

/** @brief Start the system, build the chime and play it forever. */
void app_main(void)
{
    const float pitch_hz[CHIME_NOTES] = { 1046.5f, 1318.5f, 1568.0f };  /* C6, E6 and G6 */

    kode_init();
    kode_print("Running: listen to the chime");
    for ( size_t i = 0U; (CHIME_NOTES * CHIME_NOTE_N) > i; ++i )
    {
        const float t    = (float)(i % CHIME_NOTE_N) / (float)CHIME_RATE_HZ;
        const float fade = 1.0f - ((float)(i % CHIME_NOTE_N) / (float)CHIME_NOTE_N);  /* each note dies away */

        s_samples[i] = (int16_t)(CHIME_PEAK * fade * sinf(2.0f * CHIME_PI * pitch_hz[i / CHIME_NOTE_N] * t));
    }
    (void)kode_audio_set("volume", CHIME_VOLUME);

    for ( ;; )
    {
        if ( !kode_audio_play_samples(s_samples, CHIME_NOTES * CHIME_NOTE_N) )
        {
            kode_print("no sound: %s", kode_error());
        }
        kode_delay(CHIME_PAUSE_MS);
    }
}
```

If you would rather build it yourself, follow [the steps shared by every example](/device/overview#run-the-example-of-a-page).

If you hear nothing, see [why the first sound can be lost](#gotchas).

## In the SDK

- [`kdrv/audio`](https://github.com/kodediy/kode-sdk/tree/v0.1.5/components/kdrv/audio): the ES8311 driver, with `ktone` for tones and `kwav` for files, in `kode-sdk`, described in [the ES8311 driver](/sdk/kdrv/es8311).
- [`examples/audio`](https://github.com/kodediy/kode-sdk/tree/v0.1.5/examples/audio): an SDK example for sound out and in.
