Sending .wav file in SPIFFS to server using ESP32

41 Views Asked by At

I have a .wav file saved on SPIFFS. I would like to transfer that file to a server using my esp32.

I have tried to Allocate buffer but it fail so I think it is this part that have the probelm to read the file. How can I solve this problem or there are any method to do this.

Here is my sketch:

#include <WiFi.h>
#include <HTTPClient.h>
#include <SPIFFS.h>

const char* ssid = "ssid";
const char* password = "pass";
const char* serverUrl = "http://127.0.0.1:5000/upload";

void setup() {
  Serial.begin(115200);
  delay(1000);
  
  if (!SPIFFS.begin(true)) {
    Serial.println("Failed to mount file system");
    return;
  }

  // Connect to Wi-Fi
  Serial.println("Connecting to WiFi...");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  // Send the file to the Flask server
  if (sendFileToServer("/recording.wav")) {
    Serial.println("File uploaded successfully");
  } else {
    Serial.println("Error uploading file");
  }

  // Wait for some time before sending another request
  delay(5000);
}

bool sendFileToServer(const char* filePath) {
  File file = SPIFFS.open(filePath, "r");
  if (!file) {
    Serial.println("Failed to open file");
    return false;
  }

  // Get the size of the file
  size_t fileSize = file.size();
  Serial.println(fileSize);

  // Allocate buffer to store file content
  uint8_t *fileContent = (uint8_t *)malloc(fileSize);
  if (!fileContent) {
    Serial.println("Failed to allocate memory for file content");
    file.close();
    return false;
  }

  // Read file content into the buffer
  size_t bytesRead = file.read(fileContent, fileSize);
  if (bytesRead != fileSize) {
    Serial.println("Error reading file content");
    free(fileContent);
    file.close();
    return false;
  }
  file.close();

  HTTPClient http;
  http.begin(serverUrl);
  http.addHeader("Content-Type", "audio/wav");

  // Send POST request with the file content
  int httpCode = http.POST(fileContent, fileSize);
  free(fileContent);

  if (httpCode > 0) {
    Serial.printf("[HTTP] POST... code: %d\n", httpCode);
    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println(payload);
    }
    http.end();
    return true;
  } else {
    Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
    http.end();
    return false;
  }
}

can anyone help me fix this?

0

There are 0 best solutions below