TMRh20 / TMRpcm

Arduino library for asynchronous playback of PCM/WAV files direct from SD card. Arduino Uno,Nano,Mega etc supported
http://tmrh20.blogspot.com
592 stars 178 forks source link

Get Duration Of An Audio File #141

Closed Iftikhar-Omar closed 2 years ago

Iftikhar-Omar commented 3 years ago

I'm using it on a blind assistance device. (Humanitarian Need :) )

I seriously need to get the durations of each file calculated automatedly as I must use that duration in logic. It's because whenever a file is being played it's super important in this context to finish playing that file.

Thanks, Please Help Me..

TMRh20 commented 3 years ago

For an 8-bit wav file, if you divide the file size by the sample rate, it should give you the duration in seconds:

Example for a file called "calibrat.wav":

File myFile;

void loop(){  

  if(Serial.available()){    
    if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback
      uint32_t sampleRate = 0;
      uint32_t fileSize = 0;
      float lengthInSeconds = 0.00;
      myFile = SD.open("calibrat.wav");      
      if(myFile){
        Serial.println("SD is open");
        myFile.seek(24);
        sampleRate = myFile.read();
        sampleRate |= (uint32_t)(myFile.read() << 8);
        sampleRate |= (uint32_t)(myFile.read() << 16);
        sampleRate |= (uint32_t)(myFile.read() << 24);
        fileSize = myFile.size()-44;
        lengthInSeconds = (float)(fileSize) / (float)(sampleRate) ;
        myFile.close();

      }else{
        Serial.println("cant open sd");
      }
      Serial.print("Length ");
      Serial.println(lengthInSeconds);
      tmrpcm.play("calibrat.wav");
    }
  }
}

Playback is timer-based so the actual duration may be slightly off due to timing inconsistencies, also depending on sample rate. You may need to add or subtract a bit of time to each calculation depending on how it works out in testing.

If possible, you could also use the isPlaying() function to simply detect when a file finishes playback.