在我的游戏中,我有一张地图std::map<Sound, sf::SoundBuffer> mySounds
,我将其用作声音的资源持有者。
Sound
是一个看起来像这样的枚举:
enum class Sound {
SOUND_ONE,
SOUND_TWO,
SOUND_THREE,
NUMBER_OF_SOUNDS
};
现在,为了加载我当前使用sf::SoundBuffer::loadFromFile
的声音,代码如下所示:
std::vector<std::string> paths;
paths.resize(static_cast<unsigned int>(Sound::NUMBER_OF_SOUNDS));
paths[static_cast<std::size_t>(Sound::SOUND_ONE)] = "sound1.ogg";
paths[static_cast<std::size_t>(Sound::SOUND_TWO)] = "sound2.ogg";
paths[static_cast<std::size_t>(Sound::SOUND_THREE)] = "sound3.ogg";
for (std::size_t i = 0; i < static_cast<std::size_t>(Sound::NUMBER_OF_SOUNDS); ++i) {
mySounds[static_cast<Sound>(i)].loadFromFile("./data/" + paths[i]);
}
这很好用。
现在问题:
对于我的发布版本,我想将所有声音转换为字节数组(使用名为bin2h的工具),然后使用sf::SoundBuffer::loadFromMemory()
。
数组看起来像这样:
unsigned char RES_SOUND_ONE[] = {0x4f,0x67,0x67,0x53,...};
unsigned char RES_SOUND_TWO[] = {0x52,0x88,0x29,0x47,...};
unsigned char RES_SOUND_THREE[] = {0x96,0x65,0x59,0x02,...};
如果我只有一个声音,我可以写一下:
mySound.loadFromMemory(RES_SOUND_ONE, sizeof(RES_SOUND_ONE));
它会很完美。
虽然我有多个声音,所以我想在for-loop中有一个指针(最初只是一个空指针)。
然后我根据我当前所处的循环索引将指针设置为适当的字节数组(参见下面代码中的switch
)。
然后我将指针传递给loadFromMemory
函数的数据。
for (std::size_t i = 0; i < static_cast<std::size_t>(Sound::NUMBER_OF_SOUNDS); ++i) {
void *buffer = nullptr;
switch (static_cast<Sound>(i)) {
case Sound::SOUND_ONE: { buffer = (unsigned char*)RES_SOUND_ONE; } break;
case Sound::SOUND_TWO: { buffer = (unsigned char*)RES_SOUND_TWO; } break;
case Sound::SOUND_THREE: { buffer = (unsigned char*)RES_SOUND_THREE; } break;
}
mySounds[static_cast<Sound>(i)].loadFromMemory(buffer, sizeof(buffer));
}
SFML错误消息是:
Failed to open sound file from memory (format not supported)
我做错了什么
我还尝试了其他各种事情,例如memcpy
,这一切都导致失败lol
基本上我要问的是:如何创建指向unsigned char数组的指针并将其传递给SFML函数sf::SoundBuffer::loadFromMemory(const void *data, size_t sizeInBytes)
答案 0 :(得分:1)
问题可能是您拨打loadFromMemory()
。
特别是,sizeof(buffer)
的值可能是一个常量,取决于指针占用多少内存。 (例如,64位平台上的8个字节。)
我怀疑它会大到足以包含声音信息...... :)
您想传递数组的大小。要遵循你的模式:
for (size_t i = 0; i < static_cast<size_t>(Sound::NUMBER_OF_SOUNDS); ++i)
{
unsigned char *buf = nullptr;
size_t siz = 0;
switch (static_cast<Sound>(i))
{
case Sound::SOUND_ONE:
buf = RES_SOUND_ONE;
siz = sizeof (RES_SOUND_ONE);
break;
case Sound::SOUND_TWO:
buf = RES_SOUND_TWO;
siz = sizeof (RES_SOUND_TWO);
break;
case Sound::SOUND_THREE:
buf = RES_SOUND_THREE;
siz = sizeof (RES_SOUND_THREE);
break;
}
mySounds[static_cast<Sound>(i)].loadFromMemory(buf, siz);
}