创建指向 unsigned char[] 的指针并将其传递给 sf::SoundBuffer::loadFromMemory

Create pointer to unsigned char[] and pass it to sf::SoundBuffer::loadFromMemory

在我的游戏中,我有一张地图 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 循环中有一个指针(最初只是一个空指针)。

然后我会根据我当前所在的循环索引将指针设置为适当的字节数组(参见下面代码中的 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

所以基本上我要问的是:如何创建指向无符号字符数组的指针并将其传递给 SFML 函数 sf::SoundBuffer::loadFromMemory(const void *data, size_t sizeInBytes)

问题可能出在您拨打 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);
}