some problems fixed

This commit is contained in:
2025-08-17 21:13:58 +02:00
parent d75bfcf4d0
commit b5ef9172b3
18 changed files with 1139 additions and 231 deletions

View File

@ -63,14 +63,33 @@ bool Audio::ensureStream(){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "[Audio] SDL_OpenAudioDeviceStream failed: %s", SDL_GetError());
return false;
}
// Ensure the device is running so SFX can be heard even before music starts
SDL_ResumeAudioStreamDevice(audioStream);
return true;
}
void Audio::start(){ if(!ensureStream()) return; if(!playing){ current=-1; nextTrack(); SDL_ResumeAudioStreamDevice(audioStream); playing=true; } }
void Audio::start(){
if(!ensureStream()) return;
// If no track is selected yet, try to select one now (in case tracks loaded after initial start)
if(current < 0) {
nextTrack();
}
SDL_ResumeAudioStreamDevice(audioStream);
playing = true;
}
void Audio::toggleMute(){ muted=!muted; }
void Audio::nextTrack(){ if(tracks.empty()) return; for(size_t i=0;i<tracks.size(); ++i){ current = (current + 1) % (int)tracks.size(); if(tracks[current].ok){ tracks[current].cursor=0; return; } } current=-1; }
void Audio::nextTrack(){
if(tracks.empty()) { current = -1; return; }
// Try every track once to find a decodable one
int start = current;
for(size_t i=0;i<tracks.size(); ++i){
current = (current + 1) % (int)tracks.size();
if(tracks[current].ok){ tracks[current].cursor=0; return; }
}
current=-1;
}
void Audio::feed(Uint32 bytesWanted, SDL_AudioStream* stream){
if(bytesWanted==0) return;
@ -156,7 +175,15 @@ void Audio::addTrackAsync(const std::string& path) {
}
void Audio::startBackgroundLoading() {
if (loadingThread.joinable()) return; // Already running
// If a previous loading thread exists but has finished, join it so we can start anew
if (loadingThread.joinable()) {
if (loadingComplete) {
loadingThread.join();
} else {
// Already running
return;
}
}
loadingComplete = false;
loadedCount = 0;
loadingThread = std::thread(&Audio::backgroundLoadingThread, this);
@ -174,14 +201,14 @@ void Audio::backgroundLoadingThread() {
}
#endif
// Copy pending tracks to avoid holding the mutex during processing
std::vector<std::string> tracksToProcess;
{
std::lock_guard<std::mutex> lock(pendingTracksMutex);
tracksToProcess = pendingTracks;
}
for (const std::string& path : tracksToProcess) {
while (true) {
std::string path;
{
std::lock_guard<std::mutex> lock(pendingTracksMutex);
if (pendingTracks.empty()) break;
path = std::move(pendingTracks.front());
pendingTracks.erase(pendingTracks.begin());
}
AudioTrack t;
t.path = path;
#ifdef _WIN32
@ -200,7 +227,7 @@ void Audio::backgroundLoadingThread() {
tracks.push_back(std::move(t));
}
loadedCount++;
loadedCount++;
// Small delay to prevent overwhelming the system
std::this_thread::sleep_for(std::chrono::milliseconds(10));