MCPcopy Create free account
hub / github.com/OneLoneCoder/olcPixelGameEngine / LoadFromFile

Method LoadFromFile

extensions/olcPGEX_Sound.h:233–315  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

231 }
232
233 olc::rcode SOUND::AudioSample::LoadFromFile(std::string sWavFile, olc::ResourcePack *pack)
234 {
235 auto ReadWave = [&](std::istream &is)
236 {
237 char dump[4];
238 is.read(dump, sizeof(char) * 4); // Read "RIFF"
239 if (strncmp(dump, "RIFF", 4) != 0) return olc::FAIL;
240 is.read(dump, sizeof(char) * 4); // Not Interested
241 is.read(dump, sizeof(char) * 4); // Read "WAVE"
242 if (strncmp(dump, "WAVE", 4) != 0) return olc::FAIL;
243
244 // Read Wave description chunk
245 is.read(dump, sizeof(char) * 4); // Read "fmt "
246 unsigned int nHeaderSize = 0;
247 is.read((char*)&nHeaderSize, sizeof(unsigned int)); // Not Interested
248 is.read((char*)&wavHeader, nHeaderSize);// sizeof(WAVEFORMATEX)); // Read Wave Format Structure chunk
249 // Note the -2, because the structure has 2 bytes to indicate its own size
250 // which are not in the wav file
251
252 // Just check if wave format is compatible with olcPGE
253 if (wavHeader.wBitsPerSample != 16 || wavHeader.nSamplesPerSec != 44100)
254 return olc::FAIL;
255
256 // Search for audio data chunk
257 uint32_t nChunksize = 0;
258 is.read(dump, sizeof(char) * 4); // Read chunk header
259 is.read((char*)&nChunksize, sizeof(uint32_t)); // Read chunk size
260 while (strncmp(dump, "data", 4) != 0)
261 {
262 // Not audio data, so just skip it
263 //std::fseek(f, nChunksize, SEEK_CUR);
264 is.seekg(nChunksize, std::istream::cur);
265 is.read(dump, sizeof(char) * 4);
266 is.read((char*)&nChunksize, sizeof(uint32_t));
267 }
268
269 // Finally got to data, so read it all in and convert to float samples
270 nSamples = nChunksize / (wavHeader.nChannels * (wavHeader.wBitsPerSample >> 3));
271 nChannels = wavHeader.nChannels;
272
273 // Create floating point buffer to hold audio sample
274 fSample = new float[nSamples * nChannels];
275 float *pSample = fSample;
276
277 // Read in audio data and normalise
278 for (long i = 0; i < nSamples; i++)
279 {
280 for (int c = 0; c < nChannels; c++)
281 {
282 short s = 0;
283 if (!is.eof())
284 {
285 is.read((char*)&s, sizeof(short));
286
287 *pSample = (float)s / (float)(SHRT_MAX);
288 pSample++;
289 }
290 }

Callers

nothing calls this directly

Calls 1

GetFileBufferMethod · 0.80

Tested by

no test coverage detected