CMusicHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. /*
  2. * CMusicHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include <SDL_mixer.h>
  12. #include <SDL_timer.h>
  13. #include "CMusicHandler.h"
  14. #include "CGameInfo.h"
  15. #include "renderSDL/SDLRWwrapper.h"
  16. #include "eventsSDL/InputHandler.h"
  17. #include "gui/CGuiHandler.h"
  18. #include "../lib/JsonNode.h"
  19. #include "../lib/GameConstants.h"
  20. #include "../lib/filesystem/Filesystem.h"
  21. #include "../lib/constants/StringConstants.h"
  22. #include "../lib/CRandomGenerator.h"
  23. #include "../lib/VCMIDirs.h"
  24. #include "../lib/TerrainHandler.h"
  25. #define VCMI_SOUND_NAME(x)
  26. #define VCMI_SOUND_FILE(y) #y,
  27. // sounds mapped to soundBase enum
  28. static std::string sounds[] = {
  29. "", // invalid
  30. "", // todo
  31. VCMI_SOUND_LIST
  32. };
  33. #undef VCMI_SOUND_NAME
  34. #undef VCMI_SOUND_FILE
  35. void CAudioBase::init()
  36. {
  37. if (initialized)
  38. return;
  39. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  40. {
  41. logGlobal->error("Mix_OpenAudio error: %s", Mix_GetError());
  42. return;
  43. }
  44. initialized = true;
  45. }
  46. void CAudioBase::release()
  47. {
  48. if(!(CCS->soundh->initialized && CCS->musich->initialized))
  49. Mix_CloseAudio();
  50. initialized = false;
  51. }
  52. void CAudioBase::setVolume(ui32 percent)
  53. {
  54. if (percent > 100)
  55. percent = 100;
  56. volume = percent;
  57. }
  58. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  59. {
  60. setVolume((ui32)volumeNode.Float());
  61. }
  62. CSoundHandler::CSoundHandler():
  63. listener(settings.listen["general"]["sound"]),
  64. ambientConfig(JsonPath::builtin("config/ambientSounds.json"))
  65. {
  66. listener(std::bind(&CSoundHandler::onVolumeChange, this, _1));
  67. battleIntroSounds =
  68. {
  69. soundBase::battle00, soundBase::battle01,
  70. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  71. soundBase::battle05, soundBase::battle06, soundBase::battle07
  72. };
  73. }
  74. void CSoundHandler::init()
  75. {
  76. CAudioBase::init();
  77. if(ambientConfig["allocateChannels"].isNumber())
  78. Mix_AllocateChannels((int)ambientConfig["allocateChannels"].Integer());
  79. if (initialized)
  80. {
  81. Mix_ChannelFinished([](int channel)
  82. {
  83. CCS->soundh->soundFinishedCallback(channel);
  84. });
  85. }
  86. }
  87. void CSoundHandler::release()
  88. {
  89. if (initialized)
  90. {
  91. Mix_HaltChannel(-1);
  92. for (auto &chunk : soundChunks)
  93. {
  94. if (chunk.second.first)
  95. Mix_FreeChunk(chunk.second.first);
  96. }
  97. }
  98. CAudioBase::release();
  99. }
  100. // Allocate an SDL chunk and cache it.
  101. Mix_Chunk *CSoundHandler::GetSoundChunk(const AudioPath & sound, bool cache)
  102. {
  103. try
  104. {
  105. if (cache && soundChunks.find(sound) != soundChunks.end())
  106. return soundChunks[sound].first;
  107. auto data = CResourceHandler::get()->load(sound.addPrefix("SOUNDS/"))->readAll();
  108. SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
  109. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  110. if (cache)
  111. soundChunks.insert({sound, std::make_pair (chunk, std::move (data.first))});
  112. return chunk;
  113. }
  114. catch(std::exception &e)
  115. {
  116. logGlobal->warn("Cannot get sound %s chunk: %s", sound.getOriginalName(), e.what());
  117. return nullptr;
  118. }
  119. }
  120. Mix_Chunk *CSoundHandler::GetSoundChunk(std::pair<std::unique_ptr<ui8 []>, si64> & data, bool cache)
  121. {
  122. try
  123. {
  124. std::vector<ui8> startBytes = std::vector<ui8>(data.first.get(), data.first.get() + std::min((si64)100, data.second));
  125. if (cache && soundChunksRaw.find(startBytes) != soundChunksRaw.end())
  126. return soundChunksRaw[startBytes].first;
  127. SDL_RWops *ops = SDL_RWFromMem(data.first.get(), (int)data.second);
  128. Mix_Chunk *chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  129. if (cache)
  130. soundChunksRaw.insert({startBytes, std::make_pair (chunk, std::move (data.first))});
  131. return chunk;
  132. }
  133. catch(std::exception &e)
  134. {
  135. logGlobal->warn("Cannot get sound chunk: %s", e.what());
  136. return nullptr;
  137. }
  138. }
  139. int CSoundHandler::ambientDistToVolume(int distance) const
  140. {
  141. const auto & distancesVector = ambientConfig["distances"].Vector();
  142. if(distance >= distancesVector.size())
  143. return 0;
  144. int volume = static_cast<int>(distancesVector[distance].Integer());
  145. return volume * (int)ambientConfig["volume"].Integer() / 100;
  146. }
  147. void CSoundHandler::ambientStopSound(const AudioPath & soundId)
  148. {
  149. stopSound(ambientChannels[soundId]);
  150. setChannelVolume(ambientChannels[soundId], volume);
  151. }
  152. uint32_t CSoundHandler::getSoundDurationMilliseconds(const AudioPath & sound)
  153. {
  154. if (!initialized || sound.empty())
  155. return 0;
  156. auto resourcePath = sound.addPrefix("SOUNDS/");
  157. if (!CResourceHandler::get()->existsResource(resourcePath))
  158. return 0;
  159. auto data = CResourceHandler::get()->load(resourcePath)->readAll();
  160. SDL_AudioSpec spec;
  161. uint32_t audioLen;
  162. uint8_t *audioBuf;
  163. uint32_t miliseconds = 0;
  164. if(SDL_LoadWAV_RW(SDL_RWFromMem(data.first.get(), (int)data.second), 1, &spec, &audioBuf, &audioLen) != nullptr)
  165. {
  166. SDL_FreeWAV(audioBuf);
  167. uint32_t sampleSize = SDL_AUDIO_BITSIZE(spec.format) / 8;
  168. uint32_t sampleCount = audioLen / sampleSize;
  169. uint32_t sampleLen = sampleCount / spec.channels;
  170. miliseconds = 1000 * sampleLen / spec.freq;
  171. }
  172. return miliseconds ;
  173. }
  174. // Plays a sound, and return its channel so we can fade it out later
  175. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  176. {
  177. assert(soundID < soundBase::sound_after_last);
  178. auto sound = AudioPath::builtin(sounds[soundID]);
  179. logGlobal->trace("Attempt to play sound %d with file name %s with cache", soundID, sound.getOriginalName());
  180. return playSound(sound, repeats, true);
  181. }
  182. int CSoundHandler::playSound(const AudioPath & sound, int repeats, bool cache)
  183. {
  184. if (!initialized || sound.empty())
  185. return -1;
  186. int channel;
  187. Mix_Chunk *chunk = GetSoundChunk(sound, cache);
  188. if (chunk)
  189. {
  190. channel = Mix_PlayChannel(-1, chunk, repeats);
  191. if (channel == -1)
  192. {
  193. logGlobal->error("Unable to play sound file %s , error %s", sound.getOriginalName(), Mix_GetError());
  194. if (!cache)
  195. Mix_FreeChunk(chunk);
  196. }
  197. else if (cache)
  198. initCallback(channel);
  199. else
  200. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  201. }
  202. else
  203. channel = -1;
  204. return channel;
  205. }
  206. int CSoundHandler::playSound(std::pair<std::unique_ptr<ui8 []>, si64> & data, int repeats, bool cache)
  207. {
  208. int channel = -1;
  209. if (Mix_Chunk *chunk = GetSoundChunk(data, cache))
  210. {
  211. channel = Mix_PlayChannel(-1, chunk, repeats);
  212. if (channel == -1)
  213. {
  214. logGlobal->error("Unable to play sound, error %s", Mix_GetError());
  215. if (!cache)
  216. Mix_FreeChunk(chunk);
  217. }
  218. else if (cache)
  219. initCallback(channel);
  220. else
  221. initCallback(channel, [chunk](){ Mix_FreeChunk(chunk);});
  222. }
  223. return channel;
  224. }
  225. // Helper. Randomly select a sound from an array and play it
  226. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  227. {
  228. return playSound(*RandomGeneratorUtil::nextItem(sound_vec, CRandomGenerator::getDefault()));
  229. }
  230. void CSoundHandler::stopSound(int handler)
  231. {
  232. if (initialized && handler != -1)
  233. Mix_HaltChannel(handler);
  234. }
  235. // Sets the sound volume, from 0 (mute) to 100
  236. void CSoundHandler::setVolume(ui32 percent)
  237. {
  238. CAudioBase::setVolume(percent);
  239. if (initialized)
  240. {
  241. setChannelVolume(-1, volume);
  242. for (auto const & channel : channelVolumes)
  243. updateChannelVolume(channel.first);
  244. }
  245. }
  246. void CSoundHandler::updateChannelVolume(int channel)
  247. {
  248. if (channelVolumes.count(channel))
  249. setChannelVolume(channel, getVolume() * channelVolumes[channel] / 100);
  250. else
  251. setChannelVolume(channel, getVolume());
  252. }
  253. // Sets the sound volume, from 0 (mute) to 100
  254. void CSoundHandler::setChannelVolume(int channel, ui32 percent)
  255. {
  256. Mix_Volume(channel, (MIX_MAX_VOLUME * percent)/100);
  257. }
  258. void CSoundHandler::setCallback(int channel, std::function<void()> function)
  259. {
  260. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  261. auto iter = callbacks.find(channel);
  262. //channel not found. It may have finished so fire callback now
  263. if(iter == callbacks.end())
  264. function();
  265. else
  266. iter->second.push_back(function);
  267. }
  268. void CSoundHandler::soundFinishedCallback(int channel)
  269. {
  270. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  271. if (callbacks.count(channel) == 0)
  272. return;
  273. // store callbacks from container locally - SDL might reuse this channel for another sound
  274. // but do actualy execution in separate thread, to avoid potential deadlocks in case if callback requires locks of its own
  275. auto callback = callbacks.at(channel);
  276. callbacks.erase(channel);
  277. if (!callback.empty())
  278. {
  279. GH.dispatchMainThread([callback](){
  280. for (auto entry : callback)
  281. entry();
  282. });
  283. }
  284. }
  285. void CSoundHandler::initCallback(int channel)
  286. {
  287. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  288. assert(callbacks.count(channel) == 0);
  289. callbacks[channel] = {};
  290. }
  291. void CSoundHandler::initCallback(int channel, const std::function<void()> & function)
  292. {
  293. boost::mutex::scoped_lock lockGuard(mutexCallbacks);
  294. assert(callbacks.count(channel) == 0);
  295. callbacks[channel].push_back(function);
  296. }
  297. int CSoundHandler::ambientGetRange() const
  298. {
  299. return static_cast<int>(ambientConfig["range"].Integer());
  300. }
  301. void CSoundHandler::ambientUpdateChannels(std::map<AudioPath, int> soundsArg)
  302. {
  303. boost::mutex::scoped_lock guard(mutex);
  304. std::vector<AudioPath> stoppedSounds;
  305. for(auto & pair : ambientChannels)
  306. {
  307. const auto & soundId = pair.first;
  308. const int channel = pair.second;
  309. if(!vstd::contains(soundsArg, soundId))
  310. {
  311. ambientStopSound(soundId);
  312. stoppedSounds.push_back(soundId);
  313. }
  314. else
  315. {
  316. int volume = ambientDistToVolume(soundsArg[soundId]);
  317. channelVolumes[channel] = volume;
  318. updateChannelVolume(channel);
  319. }
  320. }
  321. for(auto soundId : stoppedSounds)
  322. {
  323. channelVolumes.erase(ambientChannels[soundId]);
  324. ambientChannels.erase(soundId);
  325. }
  326. for(auto & pair : soundsArg)
  327. {
  328. const auto & soundId = pair.first;
  329. const int distance = pair.second;
  330. if(!vstd::contains(ambientChannels, soundId))
  331. {
  332. int channel = playSound(soundId, -1);
  333. int volume = ambientDistToVolume(distance);
  334. channelVolumes[channel] = volume;
  335. updateChannelVolume(channel);
  336. ambientChannels[soundId] = channel;
  337. }
  338. }
  339. }
  340. void CSoundHandler::ambientStopAllChannels()
  341. {
  342. boost::mutex::scoped_lock guard(mutex);
  343. for(auto ch : ambientChannels)
  344. {
  345. ambientStopSound(ch.first);
  346. }
  347. channelVolumes.clear();
  348. ambientChannels.clear();
  349. }
  350. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  351. {
  352. setVolume((ui32)volumeNode.Float());
  353. }
  354. CMusicHandler::CMusicHandler():
  355. listener(settings.listen["general"]["music"])
  356. {
  357. listener(std::bind(&CMusicHandler::onVolumeChange, this, _1));
  358. auto mp3files = CResourceHandler::get()->getFilteredFiles([](const ResourcePath & id) -> bool
  359. {
  360. if(id.getType() != EResType::SOUND)
  361. return false;
  362. if(!boost::algorithm::istarts_with(id.getName(), "MUSIC/"))
  363. return false;
  364. logGlobal->trace("Found music file %s", id.getName());
  365. return true;
  366. });
  367. for(const ResourcePath & file : mp3files)
  368. {
  369. if(boost::algorithm::istarts_with(file.getName(), "MUSIC/Combat"))
  370. addEntryToSet("battle", AudioPath::fromResource(file));
  371. else if(boost::algorithm::istarts_with(file.getName(), "MUSIC/AITheme"))
  372. addEntryToSet("enemy-turn", AudioPath::fromResource(file));
  373. }
  374. }
  375. void CMusicHandler::loadTerrainMusicThemes()
  376. {
  377. for (const auto & terrain : CGI->terrainTypeHandler->objects)
  378. {
  379. addEntryToSet("terrain_" + terrain->getJsonKey(), terrain->musicFilename);
  380. }
  381. }
  382. void CMusicHandler::addEntryToSet(const std::string & set, const AudioPath & musicURI)
  383. {
  384. musicsSet[set].push_back(musicURI);
  385. }
  386. void CMusicHandler::init()
  387. {
  388. CAudioBase::init();
  389. if (initialized)
  390. {
  391. Mix_HookMusicFinished([]()
  392. {
  393. CCS->musich->musicFinishedCallback();
  394. });
  395. }
  396. }
  397. void CMusicHandler::release()
  398. {
  399. if (initialized)
  400. {
  401. boost::mutex::scoped_lock guard(mutex);
  402. Mix_HookMusicFinished(nullptr);
  403. current->stop();
  404. current.reset();
  405. next.reset();
  406. }
  407. CAudioBase::release();
  408. }
  409. void CMusicHandler::playMusic(const AudioPath & musicURI, bool loop, bool fromStart)
  410. {
  411. boost::mutex::scoped_lock guard(mutex);
  412. if (current && current->isPlaying() && current->isTrack(musicURI))
  413. return;
  414. queueNext(this, "", musicURI, loop, fromStart);
  415. }
  416. void CMusicHandler::playMusicFromSet(const std::string & musicSet, const std::string & entryID, bool loop, bool fromStart)
  417. {
  418. playMusicFromSet(musicSet + "_" + entryID, loop, fromStart);
  419. }
  420. void CMusicHandler::playMusicFromSet(const std::string & whichSet, bool loop, bool fromStart)
  421. {
  422. boost::mutex::scoped_lock guard(mutex);
  423. auto selectedSet = musicsSet.find(whichSet);
  424. if (selectedSet == musicsSet.end())
  425. {
  426. logGlobal->error("Error: playing music from non-existing set: %s", whichSet);
  427. return;
  428. }
  429. if (current && current->isPlaying() && current->isSet(whichSet))
  430. return;
  431. // in this mode - play random track from set
  432. queueNext(this, whichSet, AudioPath(), loop, fromStart);
  433. }
  434. void CMusicHandler::queueNext(std::unique_ptr<MusicEntry> queued)
  435. {
  436. if (!initialized)
  437. return;
  438. next = std::move(queued);
  439. if (current.get() == nullptr || !current->stop(1000))
  440. {
  441. current.reset(next.release());
  442. current->play();
  443. }
  444. }
  445. void CMusicHandler::queueNext(CMusicHandler *owner, const std::string & setName, const AudioPath & musicURI, bool looped, bool fromStart)
  446. {
  447. queueNext(std::make_unique<MusicEntry>(owner, setName, musicURI, looped, fromStart));
  448. }
  449. void CMusicHandler::stopMusic(int fade_ms)
  450. {
  451. if (!initialized)
  452. return;
  453. boost::mutex::scoped_lock guard(mutex);
  454. if (current.get() != nullptr)
  455. current->stop(fade_ms);
  456. next.reset();
  457. }
  458. void CMusicHandler::setVolume(ui32 percent)
  459. {
  460. CAudioBase::setVolume(percent);
  461. if (initialized)
  462. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  463. }
  464. void CMusicHandler::musicFinishedCallback()
  465. {
  466. // call music restart in separate thread to avoid deadlock in some cases
  467. // It is possible for:
  468. // 1) SDL thread to call this method on end of playback
  469. // 2) VCMI code to call queueNext() method to queue new file
  470. // this leads to:
  471. // 1) SDL thread waiting to acquire music lock in this method (while keeping internal SDL mutex locked)
  472. // 2) VCMI thread waiting to acquire internal SDL mutex (while keeping music mutex locked)
  473. GH.dispatchMainThread([this]()
  474. {
  475. boost::unique_lock lockGuard(mutex);
  476. if (current.get() != nullptr)
  477. {
  478. // if music is looped, play it again
  479. if (current->play())
  480. return;
  481. else
  482. current.reset();
  483. }
  484. if (current.get() == nullptr && next.get() != nullptr)
  485. {
  486. current.reset(next.release());
  487. current->play();
  488. }
  489. });
  490. }
  491. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, const AudioPath & musicURI, bool looped, bool fromStart):
  492. owner(owner),
  493. music(nullptr),
  494. playing(false),
  495. startTime(uint32_t(-1)),
  496. startPosition(0),
  497. loop(looped ? -1 : 1),
  498. fromStart(fromStart),
  499. setName(std::move(setName))
  500. {
  501. if (!musicURI.empty())
  502. load(std::move(musicURI));
  503. }
  504. MusicEntry::~MusicEntry()
  505. {
  506. if (playing && loop > 0)
  507. {
  508. assert(0);
  509. logGlobal->error("Attempt to delete music while playing!");
  510. Mix_HaltMusic();
  511. }
  512. if (loop == 0 && Mix_FadingMusic() != MIX_NO_FADING)
  513. {
  514. assert(0);
  515. logGlobal->error("Attempt to delete music while fading out!");
  516. Mix_HaltMusic();
  517. }
  518. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  519. if (music)
  520. Mix_FreeMusic(music);
  521. }
  522. void MusicEntry::load(const AudioPath & musicURI)
  523. {
  524. if (music)
  525. {
  526. logGlobal->trace("Del-ing music file %s", currentName.getOriginalName());
  527. Mix_FreeMusic(music);
  528. music = nullptr;
  529. }
  530. if (CResourceHandler::get()->existsResource(musicURI))
  531. currentName = musicURI;
  532. else
  533. currentName = musicURI.addPrefix("MUSIC/");
  534. music = nullptr;
  535. logGlobal->trace("Loading music file %s", currentName.getOriginalName());
  536. try
  537. {
  538. auto musicFile = MakeSDLRWops(CResourceHandler::get()->load(currentName));
  539. music = Mix_LoadMUS_RW(musicFile, SDL_TRUE);
  540. }
  541. catch(std::exception &e)
  542. {
  543. logGlobal->error("Failed to load music. setName=%s\tmusicURI=%s", setName, currentName.getOriginalName());
  544. logGlobal->error("Exception: %s", e.what());
  545. }
  546. if(!music)
  547. {
  548. logGlobal->warn("Warning: Cannot open %s: %s", currentName.getOriginalName(), Mix_GetError());
  549. return;
  550. }
  551. }
  552. bool MusicEntry::play()
  553. {
  554. if (!(loop--) && music) //already played once - return
  555. return false;
  556. if (!setName.empty())
  557. {
  558. const auto & set = owner->musicsSet[setName];
  559. const auto & iter = RandomGeneratorUtil::nextItem(set, CRandomGenerator::getDefault());
  560. load(*iter);
  561. }
  562. logGlobal->trace("Playing music file %s", currentName.getOriginalName());
  563. if (!fromStart && owner->trackPositions.count(currentName) > 0 && owner->trackPositions[currentName] > 0)
  564. {
  565. float timeToStart = owner->trackPositions[currentName];
  566. startPosition = std::round(timeToStart * 1000);
  567. // erase stored position:
  568. // if music track will be interrupted again - new position will be written in stop() method
  569. // if music track is not interrupted and will finish by timeout/end of file - it will restart from begginning as it should
  570. owner->trackPositions.erase(owner->trackPositions.find(currentName));
  571. if (Mix_FadeInMusicPos(music, 1, 1000, timeToStart) == -1)
  572. {
  573. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  574. return false;
  575. }
  576. }
  577. else
  578. {
  579. startPosition = 0;
  580. if(Mix_PlayMusic(music, 1) == -1)
  581. {
  582. logGlobal->error("Unable to play music (%s)", Mix_GetError());
  583. return false;
  584. }
  585. }
  586. startTime = GH.input().getTicks();
  587. playing = true;
  588. return true;
  589. }
  590. bool MusicEntry::stop(int fade_ms)
  591. {
  592. if (Mix_PlayingMusic())
  593. {
  594. playing = false;
  595. loop = 0;
  596. uint32_t endTime = GH.input().getTicks();
  597. assert(startTime != uint32_t(-1));
  598. float playDuration = (endTime - startTime + startPosition) / 1000.f;
  599. owner->trackPositions[currentName] = playDuration;
  600. logGlobal->trace("Stopping music file %s at %f", currentName.getOriginalName(), playDuration);
  601. Mix_FadeOutMusic(fade_ms);
  602. return true;
  603. }
  604. return false;
  605. }
  606. bool MusicEntry::isPlaying()
  607. {
  608. return playing;
  609. }
  610. bool MusicEntry::isSet(std::string set)
  611. {
  612. return !setName.empty() && set == setName;
  613. }
  614. bool MusicEntry::isTrack(const AudioPath & track)
  615. {
  616. return setName.empty() && track == currentName;
  617. }