我可以使用SDL_QueueAudio()
和SDL_PauseAudioDevice()
轻松地使用这些文件播放音频。如何进行声音循环?例如启用时重复播放声音,禁用时停止播放声音?最好,我想避免使用SDL_mixer,因为我正试图了解它的内部工作原理。
audio.hpp
#include <SDL.h>
#include <cstdint>
#include <string>
class Wav
{
public:
explicit Wav(const std::string &s);
~Wav();
bool play();
private:
SDL_AudioSpec spec_;
SDL_AudioDeviceID dev_;
uint8_t *buf_;
uint32_t len_;
};
audio.cpp
#include "audio.hpp"
#include <SDL.h>
Wav::Wav(const std::string &s)
: spec_ {}, buf_ {nullptr}, len_ {0}
{
std::string path {s + ".wav"};
auto success {SDL_LoadWAV(path.c_str(), &spec_, &buf_, &len_)};
if (success == NULL)
SDL_Log("Failed to load WAV: %s", path.c_str(), SDL_GetError());
SDL_AudioSpec obtained; // format obtained
dev_ = SDL_OpenAudioDevice(nullptr, 0, &spec_, &obtained, 0);
if (dev_ == 0)
SDL_Log("Failed to open audio: %s", SDL_GetError());
}
Wav::~Wav()
{
SDL_CloseAudioDevice(dev_);
SDL_FreeWAV(buf_);
}
bool Wav::play()
{
int success {SDL_QueueAudio(dev_, buf_, len_)};
SDL_PauseAudioDevice(dev_, 0);
return success;
}