@@ -39,6 +39,8 @@ struct WaveFileHeader {
39
39
} subChunk2;
40
40
} __attribute__((packed));
41
41
42
+ struct WaveFileHeader header;
43
+
42
44
SDWaveFile::SDWaveFile () :
43
45
SDWaveFile(NULL )
44
46
{
@@ -173,6 +175,55 @@ int SDWaveFile::begin()
173
175
return 1 ;
174
176
}
175
177
178
+ int SDWaveFile::findData () {
179
+ uint8_t byteread;
180
+ int count = 0 , fileSize;
181
+ uint32_t size = 0 , data;
182
+ uint8_t buffer[] = {0 , 0 , 0 , 0 };
183
+
184
+ fileSize = _file.size () - 36 ;
185
+
186
+ // Read the first WAV header's chunk
187
+ if (_file.read (&header, 36 ) != 36 ) {
188
+ _file.close ();
189
+ return -1 ;
190
+ }
191
+
192
+ // check if "data" field is present
193
+ while (count < fileSize) {
194
+ if (_file.read ((void *)&byteread, 1 ) != 1 ) {
195
+ _file.close ();
196
+ return -1 ;
197
+ }
198
+ for (int i = 0 ; i <= 2 ; i++) {
199
+ buffer[i] = buffer[i + 1 ];
200
+ }
201
+ buffer[3 ] = byteread;
202
+ count++;
203
+
204
+ if (count >= 4 ) {
205
+ data = 0 ;
206
+ data += buffer[0 ] << 24 ;
207
+ data += buffer[1 ] << 16 ;
208
+ data += buffer[2 ] << 8 ;
209
+ data += buffer[3 ];
210
+ // if find data field read the last header part
211
+ if (data == 0x64617461 ) {
212
+ if (_file.read ((void *)&size, 4 ) != 4 ) {
213
+ _file.close ();
214
+ return -1 ;
215
+ }
216
+
217
+ // set second WAV header's chunk and return
218
+ header.subChunk2 .id = data;
219
+ header.subChunk2 .size = size;
220
+ return 1 ;
221
+ }
222
+ }
223
+ }
224
+ return -1 ;
225
+ }
226
+
176
227
int SDWaveFile::read (void * buffer, size_t size)
177
228
{
178
229
uint32_t position = _file.position ();
@@ -225,9 +276,7 @@ void SDWaveFile::readHeader()
225
276
return ;
226
277
}
227
278
228
- struct WaveFileHeader header;
229
-
230
- if (_file.read (&header, sizeof (header)) != sizeof (header)) {
279
+ if (findData () == -1 ) {
231
280
_file.close ();
232
281
return ;
233
282
}
@@ -238,7 +287,6 @@ void SDWaveFile::readHeader()
238
287
header.chunkId = __REV (header.chunkId );
239
288
header.format = __REV (header.format );
240
289
header.subChunk1 .id = __REV (header.subChunk1 .id );
241
- header.subChunk2 .id = __REV (header.subChunk2 .id );
242
290
243
291
if (header.chunkId != 0x52494646 ) { // "RIFF"
244
292
return ;
@@ -256,11 +304,6 @@ void SDWaveFile::readHeader()
256
304
return ;
257
305
}
258
306
259
- if (header.subChunk1 .size != 16 || header.subChunk1 .audioFormat != 1 ) {
260
- // not PCM
261
- return ;
262
- }
263
-
264
307
if (header.subChunk2 .id != 0x64617461 ) { // "data"
265
308
return ;
266
309
}
0 commit comments