libsdl-org / SDL_mixer

An audio mixer that supports various file formats for Simple Directmedia Layer.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using Mix_LoadMUS_RW causes crash

huabanlu opened this issue · comments

Source code from
https://lazyfoo.net/tutorials/SDL/21_sound_effects_and_music/index.php

I want to change

gMusic = Mix_LoadMUS("../test/asset/bgm1.wav");

to

std::vector<unsigned char> data; 
if (!readFileToMemory("../test/asset/bgm1.wav", data))
{
    printf("readFileToMemory error\n");
}
SDL_RWops *rwops = SDL_RWFromConstMem(data.data(), static_cast<int>(data.size()));
// gMusic = Mix_LoadMUSType_RW(rwops, Mix_MusicType::MUS_WAV, 1);
gMusic = Mix_LoadMUS_RW(rwops,1);

This will cause it to crash.

code for readFileToMemory:

bool readFileToMemory(const std::string &filePath, std::vector<unsigned char> &data)
{
	std::ifstream file(filePath, std::ios::binary | std::ios::ate);

	if (!file.is_open())
	{
		std::cerr << "Failed to open file: " << filePath << std::endl;
		return false;
	}

	std::streampos fileSize = file.tellg();
	if (fileSize <= 0)
	{
		std::cerr << "File is empty: " << filePath << std::endl;
		file.close();
		return false;
	}

	data.resize(static_cast<size_t>(fileSize));

	file.seekg(0, std::ios::beg);
	file.read(reinterpret_cast<char *>(data.data()), fileSize);
	file.close();

	return true;
}

version:
SDL2-2.28.0
SDL2_mixer-2.6.3