How do I make PlaySound load only some parts of the song C++

178 Views Asked by At

I have a 424 mb wav file, which I want to play, but it takes a lot of time to load, and it uses 425.6 mb of ram. Way too much ram for a dos format program. I want to load only a part of the song, then when it's almost at the final, load the second part, when the second part is played, remove from ram the first part, and etc. For this I should use 50 parts. Here is the line of code: PlaySound("../music/main.wav", NULL, SND_FILENAME|SND_LOOP|SND_ASYNC); I mention that I need to run this in background, while the other commands do their roles.

1

There are 1 best solutions below

0
On BEST ANSWER

PlaySound is a fairly high-level function, so it's tricky to get behavior like this. In particular, you will likely experience small silent gaps between playing back the different parts. So the best solution would be to go to a lower-level API that allows more sophisticated managing of sound playback buffers. OpenAL is a good library for doing this, the modern Windows native solution is WASAPI, which unfortunately is quite complicated to use.

With PlaySound itself, first adjust your program to load the .wav file to memory and then use SND_MEMORY for playing it from memory (example).

Now, instead of loading the whole .wav file at once, you just load the header and as many soundframes as fill your buffer. You then create your own .wav header for just those loaded samples and put it all in a contiguous buffer. You basically build your own, smaller .wav file in memory. Then you call PlaySound(..., SND_MEMORY) on that buffer. Rinse and repeat for the remaining samples from the original file.

Note that you will need your own .wav file format parser for this, but the file format is not that complicated, so hopefully this should not be too much of an issue.