AudioEngine-inl.mm 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /****************************************************************************
  2. Copyright (c) 2014-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #define LOG_TAG "AudioEngine-inl.mm"
  21. #include "platform/CCPlatformConfig.h"
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC
  23. #include "audio/apple/AudioEngine-inl.h"
  24. #import <OpenAL/alc.h>
  25. #import <AVFoundation/AVFoundation.h>
  26. #include "audio/include/AudioEngine.h"
  27. #include "platform/CCFileUtils.h"
  28. #include "base/CCDirector.h"
  29. #include "base/CCScheduler.h"
  30. #include "base/ccUtils.h"
  31. using namespace cocos2d;
  32. using namespace cocos2d::experimental;
  33. static ALCdevice *s_ALDevice = nullptr;
  34. static ALCcontext *s_ALContext = nullptr;
  35. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  36. @interface AudioEngineSessionHandler : NSObject
  37. {
  38. }
  39. -(id) init;
  40. -(void)handleInterruption:(NSNotification*)notification;
  41. @end
  42. @implementation AudioEngineSessionHandler
  43. // only enable it on iOS. Disable it on tvOS
  44. #if !defined(CC_TARGET_OS_TVOS)
  45. void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruption_state)
  46. {
  47. if (kAudioSessionBeginInterruption == interruption_state)
  48. {
  49. alcMakeContextCurrent(nullptr);
  50. }
  51. else if (kAudioSessionEndInterruption == interruption_state)
  52. {
  53. OSStatus result = AudioSessionSetActive(true);
  54. if (result) NSLog(@"Error setting audio session active! %d\n", static_cast<int>(result));
  55. alcMakeContextCurrent(s_ALContext);
  56. }
  57. }
  58. #endif
  59. -(id) init
  60. {
  61. if (self = [super init])
  62. {
  63. if ([[[UIDevice currentDevice] systemVersion] intValue] > 5) {
  64. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  65. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil];
  66. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationWillResignActiveNotification object:nil];
  67. }
  68. // only enable it on iOS. Disable it on tvOS
  69. // AudioSessionInitialize removed from tvOS
  70. #if !defined(CC_TARGET_OS_TVOS)
  71. else {
  72. AudioSessionInitialize(NULL, NULL, AudioEngineInterruptionListenerCallback, self);
  73. }
  74. #endif
  75. }
  76. return self;
  77. }
  78. -(void)handleInterruption:(NSNotification*)notification
  79. {
  80. static bool isAudioSessionInterrupted = false;
  81. static bool resumeOnBecomingActive = false;
  82. static bool pauseOnResignActive = false;
  83. if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification])
  84. {
  85. NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  86. if (reason == AVAudioSessionInterruptionTypeBegan)
  87. {
  88. isAudioSessionInterrupted = true;
  89. if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive)
  90. {
  91. ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, alcMakeContextCurrent(nullptr)");
  92. alcMakeContextCurrent(nullptr);
  93. }
  94. else
  95. {
  96. ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, pauseOnResignActive = true");
  97. pauseOnResignActive = true;
  98. }
  99. }
  100. if (reason == AVAudioSessionInterruptionTypeEnded)
  101. {
  102. isAudioSessionInterrupted = false;
  103. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
  104. {
  105. ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, alcMakeContextCurrent(s_ALContext)");
  106. NSError *error = nil;
  107. [[AVAudioSession sharedInstance] setActive:YES error:&error];
  108. alcMakeContextCurrent(s_ALContext);
  109. if (Director::getInstance()->isPaused())
  110. {
  111. ALOGD("AVAudioSessionInterruptionTypeEnded, director was paused, try to resume it.");
  112. Director::getInstance()->resume();
  113. }
  114. }
  115. else
  116. {
  117. ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, resumeOnBecomingActive = true");
  118. resumeOnBecomingActive = true;
  119. }
  120. }
  121. }
  122. else if ([notification.name isEqualToString:UIApplicationWillResignActiveNotification])
  123. {
  124. ALOGD("UIApplicationWillResignActiveNotification");
  125. if (pauseOnResignActive)
  126. {
  127. pauseOnResignActive = false;
  128. ALOGD("UIApplicationWillResignActiveNotification, alcMakeContextCurrent(nullptr)");
  129. alcMakeContextCurrent(nullptr);
  130. }
  131. }
  132. else if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification])
  133. {
  134. ALOGD("UIApplicationDidBecomeActiveNotification");
  135. if (resumeOnBecomingActive)
  136. {
  137. resumeOnBecomingActive = false;
  138. ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)");
  139. NSError *error = nil;
  140. BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error];
  141. if (!success) {
  142. ALOGE("Fail to set audio session.");
  143. return;
  144. }
  145. [[AVAudioSession sharedInstance] setActive:YES error:&error];
  146. alcMakeContextCurrent(s_ALContext);
  147. }
  148. else if (isAudioSessionInterrupted)
  149. {
  150. ALOGD("Audio session is still interrupted, pause director!");
  151. Director::getInstance()->pause();
  152. }
  153. }
  154. }
  155. -(void) dealloc
  156. {
  157. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
  158. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
  159. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
  160. [super dealloc];
  161. }
  162. @end
  163. static id s_AudioEngineSessionHandler = nullptr;
  164. #endif
  165. AudioEngineImpl::AudioEngineImpl()
  166. : _lazyInitLoop(true)
  167. , _currentAudioID(0)
  168. , _scheduler(nullptr)
  169. {
  170. }
  171. AudioEngineImpl::~AudioEngineImpl()
  172. {
  173. if (_scheduler != nullptr)
  174. {
  175. _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
  176. }
  177. if (s_ALContext) {
  178. alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
  179. _audioCaches.clear();
  180. alcMakeContextCurrent(nullptr);
  181. alcDestroyContext(s_ALContext);
  182. }
  183. if (s_ALDevice) {
  184. alcCloseDevice(s_ALDevice);
  185. }
  186. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  187. [s_AudioEngineSessionHandler release];
  188. #endif
  189. }
  190. bool AudioEngineImpl::init()
  191. {
  192. bool ret = false;
  193. do{
  194. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  195. s_AudioEngineSessionHandler = [[AudioEngineSessionHandler alloc] init];
  196. #endif
  197. s_ALDevice = alcOpenDevice(nullptr);
  198. if (s_ALDevice) {
  199. s_ALContext = alcCreateContext(s_ALDevice, nullptr);
  200. alcMakeContextCurrent(s_ALContext);
  201. alGenSources(MAX_AUDIOINSTANCES, _alSources);
  202. auto alError = alGetError();
  203. if(alError != AL_NO_ERROR)
  204. {
  205. ALOGE("%s:generating sources failed! error = %x", __PRETTY_FUNCTION__, alError);
  206. break;
  207. }
  208. for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
  209. _alSourceUsed[_alSources[i]] = false;
  210. }
  211. // fixed #16170: Random crash in alGenBuffers(AudioCache::readDataTask) at startup
  212. // Please note that, as we know the OpenAL operation is atomic (threadsafe),
  213. // 'alGenBuffers' may be invoked by different threads. But in current implementation of 'alGenBuffers',
  214. // When the first time it's invoked, application may crash!!!
  215. // Why? OpenAL is opensource by Apple and could be found at
  216. // http://opensource.apple.com/source/OpenAL/OpenAL-48.7/Source/OpenAL/oalImp.cpp .
  217. /*
  218. void InitializeBufferMap()
  219. {
  220. if (gOALBufferMap == NULL) // Position 1
  221. {
  222. gOALBufferMap = new OALBufferMap (); // Position 2
  223. // Position Gap
  224. gBufferMapLock = new CAGuard("OAL:BufferMapLock"); // Position 3
  225. gDeadOALBufferMap = new OALBufferMap ();
  226. OALBuffer *newBuffer = new OALBuffer (AL_NONE);
  227. gOALBufferMap->Add(AL_NONE, &newBuffer);
  228. }
  229. }
  230. AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids)
  231. {
  232. ...
  233. try {
  234. if (n < 0)
  235. throw ((OSStatus) AL_INVALID_VALUE);
  236. InitializeBufferMap();
  237. if (gOALBufferMap == NULL)
  238. throw ((OSStatus) AL_INVALID_OPERATION);
  239. CAGuard::Locker locked(*gBufferMapLock); // Position 4
  240. ...
  241. ...
  242. }
  243. */
  244. // 'gBufferMapLock' will be initialized in the 'InitializeBufferMap' function,
  245. // that's the problem. It means that 'InitializeBufferMap' may be invoked in different threads.
  246. // It will be very dangerous in multi-threads environment.
  247. // Imagine there're two threads (Thread A, Thread B), they call 'alGenBuffers' simultaneously.
  248. // While A goto 'Position Gap', 'gOALBufferMap' was assigned, then B goto 'Position 1' and find
  249. // that 'gOALBufferMap' isn't NULL, B just jump over 'InitialBufferMap' and goto 'Position 4'.
  250. // Meanwhile, A is still at 'Position Gap', B will crash at '*gBufferMapLock' since 'gBufferMapLock'
  251. // is still a null pointer. Oops, how could Apple implemented this method in this fucking way?
  252. // Workaround is do an unused invocation in the mainthread right after OpenAL is initialized successfully
  253. // as bellow.
  254. // ================ Workaround begin ================ //
  255. ALuint unusedAlBufferId = 0;
  256. alGenBuffers(1, &unusedAlBufferId);
  257. alDeleteBuffers(1, &unusedAlBufferId);
  258. // ================ Workaround end ================ //
  259. _scheduler = Director::getInstance()->getScheduler();
  260. ret = true;
  261. ALOGI("OpenAL was initialized successfully!");
  262. }
  263. }while (false);
  264. return ret;
  265. }
  266. AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool)> callback)
  267. {
  268. AudioCache* audioCache = nullptr;
  269. auto it = _audioCaches.find(filePath);
  270. if (it == _audioCaches.end()) {
  271. audioCache = &_audioCaches[filePath];
  272. audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  273. unsigned int cacheId = audioCache->_id;
  274. auto isCacheDestroyed = audioCache->_isDestroyed;
  275. AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){
  276. if (*isCacheDestroyed)
  277. {
  278. ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId);
  279. audioCache->setSkipReadDataTask(true);
  280. return;
  281. }
  282. audioCache->readDataTask(cacheId);
  283. });
  284. }
  285. else {
  286. audioCache = &it->second;
  287. }
  288. if (audioCache && callback)
  289. {
  290. audioCache->addLoadCallback(callback);
  291. }
  292. return audioCache;
  293. }
  294. int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
  295. {
  296. if (s_ALDevice == nullptr) {
  297. return AudioEngine::INVALID_AUDIO_ID;
  298. }
  299. bool sourceFlag = false;
  300. ALuint alSource = 0;
  301. for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
  302. alSource = _alSources[i];
  303. if ( !_alSourceUsed[alSource]) {
  304. sourceFlag = true;
  305. break;
  306. }
  307. }
  308. if(!sourceFlag){
  309. return AudioEngine::INVALID_AUDIO_ID;
  310. }
  311. auto player = new (std::nothrow) AudioPlayer;
  312. if (player == nullptr) {
  313. return AudioEngine::INVALID_AUDIO_ID;
  314. }
  315. player->_alSource = alSource;
  316. player->_loop = loop;
  317. player->_volume = volume;
  318. auto audioCache = preload(filePath, nullptr);
  319. if (audioCache == nullptr) {
  320. delete player;
  321. return AudioEngine::INVALID_AUDIO_ID;
  322. }
  323. player->setCache(audioCache);
  324. _threadMutex.lock();
  325. _audioPlayers[_currentAudioID] = player;
  326. _threadMutex.unlock();
  327. _alSourceUsed[alSource] = true;
  328. audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID));
  329. if (_lazyInitLoop) {
  330. _lazyInitLoop = false;
  331. _scheduler->schedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this, 0.05f, false);
  332. }
  333. return _currentAudioID++;
  334. }
  335. void AudioEngineImpl::_play2d(AudioCache *cache, int audioID)
  336. {
  337. //Note: It may bn in sub thread or main thread :(
  338. if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY)
  339. {
  340. _threadMutex.lock();
  341. auto playerIt = _audioPlayers.find(audioID);
  342. if (playerIt != _audioPlayers.end() && playerIt->second->play2d()) {
  343. _scheduler->performFunctionInCocosThread([audioID](){
  344. if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) {
  345. AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
  346. }
  347. });
  348. }
  349. _threadMutex.unlock();
  350. }
  351. else
  352. {
  353. ALOGD("AudioEngineImpl::_play2d, cache was destroyed or not ready!");
  354. auto iter = _audioPlayers.find(audioID);
  355. if (iter != _audioPlayers.end())
  356. {
  357. iter->second->_removeByAudioEngine = true;
  358. }
  359. }
  360. }
  361. void AudioEngineImpl::setVolume(int audioID,float volume)
  362. {
  363. auto player = _audioPlayers[audioID];
  364. player->_volume = volume;
  365. if (player->_ready) {
  366. alSourcef(_audioPlayers[audioID]->_alSource, AL_GAIN, volume);
  367. auto error = alGetError();
  368. if (error != AL_NO_ERROR) {
  369. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  370. }
  371. }
  372. }
  373. void AudioEngineImpl::setLoop(int audioID, bool loop)
  374. {
  375. auto player = _audioPlayers[audioID];
  376. if (player->_ready) {
  377. if (player->_streamingSource) {
  378. player->setLoop(loop);
  379. } else {
  380. if (loop) {
  381. alSourcei(player->_alSource, AL_LOOPING, AL_TRUE);
  382. } else {
  383. alSourcei(player->_alSource, AL_LOOPING, AL_FALSE);
  384. }
  385. auto error = alGetError();
  386. if (error != AL_NO_ERROR) {
  387. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  388. }
  389. }
  390. }
  391. else {
  392. player->_loop = loop;
  393. }
  394. }
  395. bool AudioEngineImpl::pause(int audioID)
  396. {
  397. bool ret = true;
  398. alSourcePause(_audioPlayers[audioID]->_alSource);
  399. auto error = alGetError();
  400. if (error != AL_NO_ERROR) {
  401. ret = false;
  402. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  403. }
  404. return ret;
  405. }
  406. bool AudioEngineImpl::resume(int audioID)
  407. {
  408. bool ret = true;
  409. alSourcePlay(_audioPlayers[audioID]->_alSource);
  410. auto error = alGetError();
  411. if (error != AL_NO_ERROR) {
  412. ret = false;
  413. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  414. }
  415. return ret;
  416. }
  417. void AudioEngineImpl::stop(int audioID)
  418. {
  419. auto player = _audioPlayers[audioID];
  420. player->destroy();
  421. //Note: Don't set the flag to false here, it should be set in 'update' function.
  422. // Otherwise, the state got from alSourceState may be wrong
  423. // _alSourceUsed[player->_alSource] = false;
  424. }
  425. void AudioEngineImpl::stopAll()
  426. {
  427. for(auto&& player : _audioPlayers)
  428. {
  429. player.second->destroy();
  430. }
  431. //Note: Don't set the flag to false here, it should be set in 'update' function.
  432. // Otherwise, the state got from alSourceState may be wrong
  433. // for(int index = 0; index < MAX_AUDIOINSTANCES; ++index)
  434. // {
  435. // _alSourceUsed[_alSources[index]] = false;
  436. // }
  437. }
  438. float AudioEngineImpl::getDuration(int audioID)
  439. {
  440. auto player = _audioPlayers[audioID];
  441. if(player->_ready){
  442. return player->_audioCache->_duration;
  443. } else {
  444. return AudioEngine::TIME_UNKNOWN;
  445. }
  446. }
  447. float AudioEngineImpl::getCurrentTime(int audioID)
  448. {
  449. float ret = 0.0f;
  450. auto player = _audioPlayers[audioID];
  451. if(player->_ready){
  452. if (player->_streamingSource) {
  453. ret = player->getTime();
  454. } else {
  455. alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret);
  456. auto error = alGetError();
  457. if (error != AL_NO_ERROR) {
  458. ALOGE("%s, audio id:%d,error code:%x", __PRETTY_FUNCTION__,audioID,error);
  459. }
  460. }
  461. }
  462. return ret;
  463. }
  464. bool AudioEngineImpl::setCurrentTime(int audioID, float time)
  465. {
  466. bool ret = false;
  467. auto player = _audioPlayers[audioID];
  468. do {
  469. if (!player->_ready) {
  470. break;
  471. }
  472. if (player->_streamingSource) {
  473. ret = player->setTime(time);
  474. break;
  475. }
  476. else {
  477. if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames &&
  478. (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) {
  479. ALOGE("%s: audio id = %d", __PRETTY_FUNCTION__,audioID);
  480. break;
  481. }
  482. alSourcef(player->_alSource, AL_SEC_OFFSET, time);
  483. auto error = alGetError();
  484. if (error != AL_NO_ERROR) {
  485. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  486. }
  487. ret = true;
  488. }
  489. } while (0);
  490. return ret;
  491. }
  492. void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  493. {
  494. _audioPlayers[audioID]->_finishCallbak = callback;
  495. }
  496. void AudioEngineImpl::update(float dt)
  497. {
  498. ALint sourceState;
  499. int audioID;
  500. AudioPlayer* player;
  501. ALuint alSource;
  502. // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size());
  503. for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) {
  504. audioID = it->first;
  505. player = it->second;
  506. alSource = player->_alSource;
  507. alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState);
  508. if (player->_removeByAudioEngine)
  509. {
  510. AudioEngine::remove(audioID);
  511. _threadMutex.lock();
  512. it = _audioPlayers.erase(it);
  513. _threadMutex.unlock();
  514. delete player;
  515. _alSourceUsed[alSource] = false;
  516. }
  517. else if (player->_ready && sourceState == AL_STOPPED) {
  518. std::string filePath;
  519. if (player->_finishCallbak) {
  520. auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
  521. filePath = *audioInfo.filePath;
  522. }
  523. AudioEngine::remove(audioID);
  524. _threadMutex.lock();
  525. it = _audioPlayers.erase(it);
  526. _threadMutex.unlock();
  527. if (player->_finishCallbak) {
  528. player->_finishCallbak(audioID, filePath); //FIXME: callback will delay 50ms
  529. }
  530. delete player;
  531. _alSourceUsed[alSource] = false;
  532. }
  533. else{
  534. ++it;
  535. }
  536. }
  537. if(_audioPlayers.empty()){
  538. _lazyInitLoop = true;
  539. _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
  540. }
  541. }
  542. void AudioEngineImpl::uncache(const std::string &filePath)
  543. {
  544. _audioCaches.erase(filePath);
  545. }
  546. void AudioEngineImpl::uncacheAll()
  547. {
  548. _audioCaches.clear();
  549. }
  550. #endif