This project turns an ESP32 into a voice-activated AI chatbot that listens for commands, sends audio to OpenAI's API, and speaks responses through a speaker. The system uses an I²S microphone to capture audio, processes it over WiFi, and plays back AI-generated speech through a Class-D amplifier and speaker.
The guide provides a complete wiring diagram showing microphone and amplifier connections to the ESP32, a full parts list, Arduino firmware with WebSocket communication and I²S audio handling, and step-by-step assembly instructions. Builders will learn how to configure WiFi credentials and API keys, wire I²S audio peripherals, and integrate cloud-based AI into an embedded system.
Wiring diagram
Gather all the parts
Assemble it in 4 steps
1. Connect the microphone
With USB unplugged, connect VDD to 3V3, GND and L/R to GND. SCK goes to GPIO26 (clock), WS to GPIO25 (audio timing), and SD to GPIO33 (microphone data).
- Never connect the microphone to 5V; that can damage it.
2. Connect the speaker amplifier
Connect VIN to 3V3 (lower-volume operation) and GND to GND. BCLK goes to GPIO27 (clock), LRC to GPIO14 (audio timing), DIN to GPIO22 (sound data), and SD to 3V3 (enable left channel). Leave GAIN unconnected. Connect SPK+ to speaker POS and SPK- to speaker NEG. Use an 8 ohm 3 W speaker.
- Neither speaker terminal may connect to GND. This can damage the amplifier.
3. Add the talk button
Connect the button between GPIO32 and GND. For a four-leg switch, use legs on opposite switch contacts, not two internally joined legs. Keep the microphone away from the speaker.
4. Check before powering
Check every power wire before connecting USB power to the board. Use short audio wires and a reliable USB power source.
Review all connections
1. Connections between "mic" and "ESP32"
2. Connections between "amp" and "ESP32"
3. Connections between "talk" and "ESP32"
Deploy the firmware
#include <Arduino.h>
#include <WiFi.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <driver/i2s.h>
#include <mbedtls/base64.h>
#include <time.h>
#include "cert.h"
// ESP32 DevKit v1: mic BCLK26/WS25/DATA33; amp BCLK27/WS14/DATA22; button32.
// Fill these locally before Deploy. Never share your API key in chat.
const char* WIFI_NAME = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* API_KEY = "YOUR_OPENAI_API_KEY";
WebSocketsClient ws;
String headers;
bool ready=false, recording=false, answering=false;
uint32_t samples=0, started=0;
void sendEvent(const char* s){ws.sendTXT(s);}
void audioInit(i2s_port_t port, bool input){
i2s_config_t c={};
c.mode=(i2s_mode_t)(I2S_MODE_MASTER | (input?I2S_MODE_RX:I2S_MODE_TX));
c.sample_rate=24000; c.bits_per_sample=input?I2S_BITS_PER_SAMPLE_32BIT:I2S_BITS_PER_SAMPLE_16BIT;
c.channel_format=I2S_CHANNEL_FMT_ONLY_LEFT; c.communication_format=I2S_COMM_FORMAT_STAND_I2S;
c.intr_alloc_flags=0; c.dma_buf_count=8; c.dma_buf_len=256; c.tx_desc_auto_clear=true;
i2s_pin_config_t p={}; p.bck_io_num=input?26:27; p.ws_io_num=input?25:14;
p.data_out_num=input?I2S_PIN_NO_CHANGE:22; p.data_in_num=input?33:I2S_PIN_NO_CHANGE;
if(i2s_driver_install(port,&c,0,nullptr)!=ESP_OK || i2s_set_pin(port,&p)!=ESP_OK){Serial.println("Audio initialization failed");while(true)delay(1000);}
if(!input)i2s_zero_dma_buffer(port);
}
void receive(WStype_t type,uint8_t* payload,size_t len){
if(type==WStype_DISCONNECTED){ready=false;recording=false;answering=false;Serial.println("Disconnected; reconnecting");return;}
if(type==WStype_CONNECTED){
sendEvent(R"JSON({"type":"session.update","session":{"type":"realtime","output_modalities":["audio"],"instructions":"Give brief helpful spoken answers in the language the user speaks. Your voice is AI-generated.","audio":{"input":{"format":{"type":"audio/pcm","rate":24000},"turn_detection":null},"output":{"format":{"type":"audio/pcm","rate":24000},"voice":"marin"}}}})JSON");return;
}
if(type!=WStype_TEXT)return;
JsonDocument doc; if(deserializeJson(doc,payload,len)){Serial.println("Invalid or oversized server message");return;}
const char* event=doc["type"] | "";
if(!strcmp(event,"session.updated")){ready=true;Serial.println("Ready: hold button, speak, release.");}
else if(!strcmp(event,"response.output_audio.delta")){
const char* encoded=doc["delta"] | ""; size_t n=strlen(encoded), out=0;
uint8_t* pcm=(uint8_t*)malloc(n*3/4+4);
if(!pcm){Serial.println("Audio memory exhausted");return;}
if(mbedtls_base64_decode(pcm,n*3/4+4,&out,(const uint8_t*)encoded,n)==0){
int16_t* values=(int16_t*)pcm; for(size_t i=0;i<out/2;i++)values[i]/=4;
size_t written=0; i2s_write(I2S_NUM_1,pcm,out,&written,pdMS_TO_TICKS(3000));
} free(pcm);
}
else if(!strcmp(event,"response.done")){answering=false;Serial.println("Reply finished. Hold button for next question.");}
else if(!strcmp(event,"error")){serializeJson(doc,Serial);Serial.println();answering=false;}
}
void setup(){
Serial.begin(115200);pinMode(32,INPUT_PULLUP);
audioInit(I2S_NUM_0,true);audioInit(I2S_NUM_1,false);
if(!strcmp(WIFI_NAME,"YOUR_WIFI_NAME") || !strcmp(API_KEY,"YOUR_OPENAI_API_KEY")){
Serial.println("Set WIFI_NAME, WIFI_PASSWORD and API_KEY in src/main.cpp, then Deploy.");return;}
WiFi.begin(WIFI_NAME,WIFI_PASSWORD);Serial.println("Connecting to Wi-Fi");
uint32_t t=millis();while(WiFi.status()!=WL_CONNECTED && millis()-t<30000)delay(250);
if(WiFi.status()!=WL_CONNECTED){Serial.println("Wi-Fi failed. Check settings and reset.");return;}
configTime(0,0,"pool.ntp.org","time.google.com");t=millis();
while(time(nullptr)<1700000000 && millis()-t<20000)delay(100);
if(time(nullptr)<1700000000){Serial.println("Clock sync failed; reset to retry securely.");return;}
headers="Authorization: Bearer ";headers+=API_KEY;headers+="\r\n";
ws.setExtraHeaders(headers.c_str());ws.onEvent(receive);ws.setReconnectInterval(5000);
ws.beginSslWithCA("api.openai.com",443,"/v1/realtime?model=gpt-realtime-2.1-mini",ROOT_CA);
}
void loop(){
ws.loop();
bool pressed=digitalRead(32)==LOW;
if(ready && !answering && pressed && !recording){
delay(20);if(digitalRead(32)!=LOW)return;
recording=true;samples=0;started=millis();sendEvent("{\"type\":\"input_audio_buffer.clear\"}");Serial.println("Listening (maximum 15 seconds)");
// Drop stale samples queued while idle.
int32_t discard[256];size_t n;for(int i=0;i<8;i++)i2s_read(I2S_NUM_0,discard,sizeof(discard),&n,0);
}
if(recording){
int32_t raw[480];int16_t pcm[480];size_t bytes=0;
i2s_read(I2S_NUM_0,raw,sizeof(raw),&bytes,pdMS_TO_TICKS(25));
size_t count=bytes/4;
for(size_t i=0;i<count;i++){int32_t v=raw[i]>>14;pcm[i]=(int16_t)constrain(v,-32768,32767);}
if(count){unsigned char encoded[1284];size_t n=0;mbedtls_base64_encode(encoded,sizeof(encoded),&n,(uint8_t*)pcm,count*2);encoded[n]=0;
String message="{\"type\":\"input_audio_buffer.append\",\"audio\":\"";message+=(char*)encoded;message+="\"}";ws.sendTXT(message);samples+=count;}
if(!pressed || millis()-started>=15000){recording=false;
if(samples>=2400){sendEvent("{\"type\":\"input_audio_buffer.commit\"}");sendEvent("{\"type\":\"response.create\"}");answering=true;Serial.println("Waiting for spoken answer");}
else sendEvent("{\"type\":\"input_audio_buffer.clear\"}");
while(digitalRead(32)==LOW){ws.loop();delay(5);}
}
}else delay(2);
}Remix this project
Make it yours in one click
Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.




