Skip to content

Commit 4eaa579

Browse files
committed
Fixes volume
1 parent efb4d92 commit 4eaa579

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

usb-audio/main/main.c

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,31 @@ static i2s_chan_handle_t rx;
2828
static i2s_chan_handle_t tx;
2929

3030
static bool is_muted = false;
31-
static uint32_t volume = 100;
31+
// volume is in dB
32+
static uint32_t volume = 0;
33+
static uint32_t volume_factor = 100;
3234

3335
static esp_err_t usb_uac_device_output_cb(uint8_t *buf, size_t len, void *arg)
3436
{
3537
if (!tx) {
3638
return ESP_FAIL;
3739
}
40+
int16_t *samples = (int16_t *)buf;
41+
for (size_t i = 0; i < len / 2; i++) {
42+
if (is_muted) {
43+
samples[i] = 0;
44+
continue;
45+
}
46+
int32_t sample = samples[i];
47+
// volume is in dB
48+
sample = (sample * volume_factor) / 100;
49+
if (sample > 32767) {
50+
sample = 32767;
51+
} else if (sample < -32768) {
52+
sample = -32768;
53+
}
54+
samples[i] = (int16_t)sample;
55+
}
3856
size_t total_bytes_written = 0;
3957
while (total_bytes_written < len) {
4058
size_t bytes_written = 0;
@@ -54,17 +72,16 @@ static esp_err_t usb_uac_device_input_cb(uint8_t *buf, size_t len, size_t *bytes
5472

5573
static void usb_uac_device_set_mute_cb(uint32_t mute, void *arg)
5674
{
57-
// this seems to be handled by the OS - are we supposed to do anything with it?
5875
is_muted = mute;
5976
}
60-
6177
static void usb_uac_device_set_volume_cb(uint32_t _volume, void *arg)
6278
{
63-
// this also seems to be handled by the OS - are we supposed to do anything with it?
64-
volume = _volume;
79+
// see here for what is going on here: https://github.com/espressif/esp-iot-solution/blob/36d8130e8e880720108de2c31ce0779827b1bcd9/components/usb/usb_device_uac/usb_device_uac.c#L259
80+
// _volume = (volume_db + 50) * 2
81+
int volume_db = _volume / 2 - 50;
82+
volume_factor = pow(10, volume_db / 20.0f) * 100.0f;
6583
}
6684

67-
6885
static void usb_uac_device_init(void)
6986
{
7087
uac_device_config_t config = {

0 commit comments

Comments
 (0)