Programing while (file.available())

Hi guys,

I have a function getFile for get file MP3 from micro sd.
My problem is when calling the function and run on while (file.available()) and same time together any request from client, server.handleClient() cannot running well (I think still loop on while (file.available())).
server.handleClient() will be running after finished loop while (file.available()) .

How do I run both codes at the same time?

void getFile(const String& path, const String& contentType) {
  File file = SD.open(path);
  if (!file) {
    String json = "{\"message\": \"Hello, ESP32!\", \"status\": \"success\"}";
    server.send(200, "application/json", json);
    return;
  }

  size_t fileSize = file.size();
  server.setContentLength(fileSize);
  server.sendHeader("Content-Type", contentType);
  server.sendHeader("Cache-Control", "public, jws_AR=31536000");  // Cache for 1 years
  server.sendHeader("Connection", "close");
  server.send(200, contentType, "");

  const size_t bufferSize = 512;  // Size of each chunk
  uint8_t buffer[bufferSize];
  while (file.available()) {
    // server.handleClient();
    if (!_StopMp3) {
      size_t bytesRead = file.read(buffer, bufferSize);
      // Serial.print("Bytes read: ");
      // Serial.println(bytesRead);
      server.client().write(buffer, bytesRead);
    }
    if (_StopMp3) {
      _StopMp3 = false;
      Serial.println("STOP PLAY");
      break;
    }
  }
  file.close();
}

Have you considered using if (file.available()) instead of while (file.available()) ?

Hi Bro,

Thansk for you response.

Am tried to file.available(). the file not load from esp.

what is server.handleClient()? can't you add it into the while loop?

Hi Juraj,

I tried also add server.handleClient() into while loop is not working.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.