I am reading WAVE files into memory and then playing them whenever needed
I wrote this implementation for loading the file into memory:
SDL_RWops* RawData = SDL_RWFromFile("Demo.wav", "rb");
if (!RawData)
{
Error::Set("Could not read music file");
return;
}
const Sint64 DataSize = SDL_RWsize(RawData);
Data = malloc(DataSize);
if (!Data)
{
Error::Set("Failed to load music file");
return;
}
SDL_RWread(RawData, Data, DataSize, 1);
SDL_RWclose(RawData);
music = Mix_LoadMUSType_RW(SDL_RWFromConstMem(Data, DataSize), MUS_NONE, true);
However I found a code example to load an entire file into memory and the code is a bit different:
SDL_RWops *rw = SDL_RWFromFile(filename, "rb");
if (rw == NULL) return NULL;
Sint64 res_size = SDL_RWsize(rw);
char* res = (char*)malloc(res_size + 1);
Sint64 nb_read_total = 0, nb_read = 1;
char* buf = res;
while (nb_read_total < res_size && nb_read != 0) {
nb_read = SDL_RWread(rw, buf, 1, (res_size - nb_read_total));
nb_read_total += nb_read;
buf += nb_read;
}
SDL_RWclose(rw);
if (nb_read_total != res_size) {
free(res);
return NULL;
}
res[nb_read_total] = '\0';
return res;
Testing both of the codes.. I found that my implementation uses slightly more memory but both of them work ( Music is played )
So I want to know if there is any difference in both of them
And is my first method to load entire file into memory is right