Fixed some thread safety issues in Sound.

This commit is contained in:
Leon Styhre 2021-11-15 23:27:02 +01:00
parent 81d6f0fd30
commit 7b06e9fb8b
2 changed files with 13 additions and 1 deletions

View file

@ -151,6 +151,8 @@ void Sound::play()
SDL_LockAudioDevice(AudioManager::sAudioDevice);
std::unique_lock<std::mutex> playerLock(mMutex);
if (mPlaying)
// Replay from start. rewind the sample to the beginning.
mSamplePos = 0;
@ -158,6 +160,8 @@ void Sound::play()
// Flag our sample as playing.
mPlaying = true;
playerLock.unlock();
SDL_UnlockAudioDevice(AudioManager::sAudioDevice);
// Tell the AudioManager to start playing samples.
AudioManager::getInstance().play();
@ -167,6 +171,7 @@ void Sound::stop()
{
// Flag our sample as not playing and rewind its position.
SDL_LockAudioDevice(AudioManager::sAudioDevice);
std::unique_lock<std::mutex> playerLock(mMutex);
mPlaying = false;
mSamplePos = 0;
SDL_UnlockAudioDevice(AudioManager::sAudioDevice);
@ -177,6 +182,7 @@ void Sound::setPosition(Uint32 newPosition)
mSamplePos = newPosition;
if (mSamplePos >= mSampleLength) {
// Got to or beyond the end of the sample. stop playing.
std::unique_lock<std::mutex> playerLock(mMutex);
mPlaying = false;
mSamplePos = 0;
}

View file

@ -13,6 +13,7 @@
#include <SDL2/SDL_audio.h>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
@ -30,7 +31,11 @@ public:
void loadFile(const std::string& path);
void play();
bool isPlaying() const { return mPlaying; }
bool isPlaying() const
{
std::unique_lock<std::mutex> playerLock(mMutex);
return mPlaying;
}
void stop();
const Uint8* getData() const { return mSampleData; }
@ -46,6 +51,7 @@ public:
private:
Sound(const std::string& path = "");
inline static std::mutex mMutex;
static std::map<std::string, std::shared_ptr<Sound>> sMap;
std::string mPath;
SDL_AudioSpec mSampleFormat;