AudioEngine-inl.mm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. static AudioEngineImpl* s_instance = nullptr;
  36. typedef ALvoid (*alSourceNotificationProc)(ALuint sid, ALuint notificationID, ALvoid* userData);
  37. typedef ALenum (*alSourceAddNotificationProcPtr)(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData);
  38. static ALenum alSourceAddNotificationExt(ALuint sid, ALuint notificationID, alSourceNotificationProc notifyProc, ALvoid* userData)
  39. {
  40. static alSourceAddNotificationProcPtr proc = nullptr;
  41. if (proc == nullptr)
  42. {
  43. proc = (alSourceAddNotificationProcPtr)alcGetProcAddress(nullptr, "alSourceAddNotification");
  44. }
  45. if (proc)
  46. {
  47. return proc(sid, notificationID, notifyProc, userData);
  48. }
  49. return AL_INVALID_VALUE;
  50. }
  51. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  52. @interface AudioEngineSessionHandler : NSObject
  53. {
  54. }
  55. -(id) init;
  56. -(void)handleInterruption:(NSNotification*)notification;
  57. @end
  58. @implementation AudioEngineSessionHandler
  59. // only enable it on iOS. Disable it on tvOS
  60. #if !defined(CC_TARGET_OS_TVOS)
  61. void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruption_state)
  62. {
  63. if (kAudioSessionBeginInterruption == interruption_state)
  64. {
  65. alcMakeContextCurrent(nullptr);
  66. }
  67. else if (kAudioSessionEndInterruption == interruption_state)
  68. {
  69. OSStatus result = AudioSessionSetActive(true);
  70. if (result) NSLog(@"Error setting audio session active! %d\n", static_cast<int>(result));
  71. alcMakeContextCurrent(s_ALContext);
  72. }
  73. }
  74. #endif
  75. -(id) init
  76. {
  77. if (self = [super init])
  78. {
  79. if ([[[UIDevice currentDevice] systemVersion] intValue] > 5) {
  80. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationWillResignActiveNotification object:nil];
  83. }
  84. // only enable it on iOS. Disable it on tvOS
  85. // AudioSessionInitialize removed from tvOS
  86. #if !defined(CC_TARGET_OS_TVOS)
  87. else {
  88. AudioSessionInitialize(NULL, NULL, AudioEngineInterruptionListenerCallback, self);
  89. }
  90. #endif
  91. BOOL success = [[AVAudioSession sharedInstance]
  92. setCategory: AVAudioSessionCategoryAmbient
  93. error: nil];
  94. if (!success)
  95. ALOGE("Fail to set audio session.");
  96. }
  97. return self;
  98. }
  99. -(void)handleInterruption:(NSNotification*)notification
  100. {
  101. static bool isAudioSessionInterrupted = false;
  102. static bool resumeOnBecomingActive = false;
  103. static bool pauseOnResignActive = false;
  104. if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification])
  105. {
  106. NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  107. if (reason == AVAudioSessionInterruptionTypeBegan)
  108. {
  109. isAudioSessionInterrupted = true;
  110. if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive)
  111. {
  112. ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, alcMakeContextCurrent(nullptr)");
  113. alcMakeContextCurrent(nullptr);
  114. }
  115. else
  116. {
  117. ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, pauseOnResignActive = true");
  118. pauseOnResignActive = true;
  119. }
  120. }
  121. if (reason == AVAudioSessionInterruptionTypeEnded)
  122. {
  123. isAudioSessionInterrupted = false;
  124. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
  125. {
  126. ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, alcMakeContextCurrent(s_ALContext)");
  127. NSError *error = nil;
  128. [[AVAudioSession sharedInstance] setActive:YES error:&error];
  129. alcMakeContextCurrent(s_ALContext);
  130. if (Director::getInstance()->isPaused())
  131. {
  132. ALOGD("AVAudioSessionInterruptionTypeEnded, director was paused, try to resume it.");
  133. Director::getInstance()->resume();
  134. }
  135. }
  136. else
  137. {
  138. ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, resumeOnBecomingActive = true");
  139. resumeOnBecomingActive = true;
  140. }
  141. }
  142. }
  143. else if ([notification.name isEqualToString:UIApplicationWillResignActiveNotification])
  144. {
  145. ALOGD("UIApplicationWillResignActiveNotification");
  146. if (pauseOnResignActive)
  147. {
  148. pauseOnResignActive = false;
  149. ALOGD("UIApplicationWillResignActiveNotification, alcMakeContextCurrent(nullptr)");
  150. alcMakeContextCurrent(nullptr);
  151. }
  152. }
  153. else if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification])
  154. {
  155. ALOGD("UIApplicationDidBecomeActiveNotification");
  156. if (resumeOnBecomingActive)
  157. {
  158. resumeOnBecomingActive = false;
  159. ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)");
  160. NSError *error = nil;
  161. BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error];
  162. if (!success) {
  163. ALOGE("Fail to set audio session.");
  164. return;
  165. }
  166. [[AVAudioSession sharedInstance] setActive:YES error:&error];
  167. alcMakeContextCurrent(s_ALContext);
  168. }
  169. else if (isAudioSessionInterrupted)
  170. {
  171. ALOGD("Audio session is still interrupted, pause director!");
  172. Director::getInstance()->pause();
  173. }
  174. }
  175. }
  176. -(void) dealloc
  177. {
  178. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
  179. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
  180. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
  181. [super dealloc];
  182. }
  183. @end
  184. static id s_AudioEngineSessionHandler = nullptr;
  185. #endif
  186. ALvoid AudioEngineImpl::myAlSourceNotificationCallback(ALuint sid, ALuint notificationID, ALvoid* userData)
  187. {
  188. // Currently, we only care about AL_BUFFERS_PROCESSED event
  189. if (notificationID != AL_BUFFERS_PROCESSED)
  190. return;
  191. AudioPlayer* player = nullptr;
  192. s_instance->_threadMutex.lock();
  193. for (const auto& e : s_instance->_audioPlayers)
  194. {
  195. player = e.second;
  196. if (player->_alSource == sid && player->_streamingSource)
  197. {
  198. player->wakeupRotateThread();
  199. }
  200. }
  201. s_instance->_threadMutex.unlock();
  202. }
  203. AudioEngineImpl::AudioEngineImpl()
  204. : _lazyInitLoop(true)
  205. , _currentAudioID(0)
  206. , _scheduler(nullptr)
  207. {
  208. s_instance = this;
  209. }
  210. AudioEngineImpl::~AudioEngineImpl()
  211. {
  212. if (_scheduler != nullptr)
  213. {
  214. _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
  215. }
  216. if (s_ALContext) {
  217. alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
  218. _audioCaches.clear();
  219. alcMakeContextCurrent(nullptr);
  220. alcDestroyContext(s_ALContext);
  221. }
  222. if (s_ALDevice) {
  223. alcCloseDevice(s_ALDevice);
  224. }
  225. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  226. [s_AudioEngineSessionHandler release];
  227. #endif
  228. s_instance = nullptr;
  229. }
  230. bool AudioEngineImpl::init()
  231. {
  232. bool ret = false;
  233. do{
  234. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  235. s_AudioEngineSessionHandler = [[AudioEngineSessionHandler alloc] init];
  236. #endif
  237. s_ALDevice = alcOpenDevice(nullptr);
  238. if (s_ALDevice) {
  239. s_ALContext = alcCreateContext(s_ALDevice, nullptr);
  240. alcMakeContextCurrent(s_ALContext);
  241. alGenSources(MAX_AUDIOINSTANCES, _alSources);
  242. auto alError = alGetError();
  243. if(alError != AL_NO_ERROR)
  244. {
  245. ALOGE("%s:generating sources failed! error = %x", __PRETTY_FUNCTION__, alError);
  246. break;
  247. }
  248. for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
  249. _unusedSourcesPool.push_back(_alSources[i]);
  250. alSourceAddNotificationExt(_alSources[i], AL_BUFFERS_PROCESSED, myAlSourceNotificationCallback, nullptr);
  251. }
  252. // fixed #16170: Random crash in alGenBuffers(AudioCache::readDataTask) at startup
  253. // Please note that, as we know the OpenAL operation is atomic (threadsafe),
  254. // 'alGenBuffers' may be invoked by different threads. But in current implementation of 'alGenBuffers',
  255. // When the first time it's invoked, application may crash!!!
  256. // Why? OpenAL is opensource by Apple and could be found at
  257. // http://opensource.apple.com/source/OpenAL/OpenAL-48.7/Source/OpenAL/oalImp.cpp .
  258. /*
  259. void InitializeBufferMap()
  260. {
  261. if (gOALBufferMap == NULL) // Position 1
  262. {
  263. gOALBufferMap = new OALBufferMap (); // Position 2
  264. // Position Gap
  265. gBufferMapLock = new CAGuard("OAL:BufferMapLock"); // Position 3
  266. gDeadOALBufferMap = new OALBufferMap ();
  267. OALBuffer *newBuffer = new OALBuffer (AL_NONE);
  268. gOALBufferMap->Add(AL_NONE, &newBuffer);
  269. }
  270. }
  271. AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids)
  272. {
  273. ...
  274. try {
  275. if (n < 0)
  276. throw ((OSStatus) AL_INVALID_VALUE);
  277. InitializeBufferMap();
  278. if (gOALBufferMap == NULL)
  279. throw ((OSStatus) AL_INVALID_OPERATION);
  280. CAGuard::Locker locked(*gBufferMapLock); // Position 4
  281. ...
  282. ...
  283. }
  284. */
  285. // 'gBufferMapLock' will be initialized in the 'InitializeBufferMap' function,
  286. // that's the problem. It means that 'InitializeBufferMap' may be invoked in different threads.
  287. // It will be very dangerous in multi-threads environment.
  288. // Imagine there're two threads (Thread A, Thread B), they call 'alGenBuffers' simultaneously.
  289. // While A goto 'Position Gap', 'gOALBufferMap' was assigned, then B goto 'Position 1' and find
  290. // that 'gOALBufferMap' isn't NULL, B just jump over 'InitialBufferMap' and goto 'Position 4'.
  291. // Meanwhile, A is still at 'Position Gap', B will crash at '*gBufferMapLock' since 'gBufferMapLock'
  292. // is still a null pointer. Oops, how could Apple implemented this method in this fucking way?
  293. // Workaround is do an unused invocation in the mainthread right after OpenAL is initialized successfully
  294. // as bellow.
  295. // ================ Workaround begin ================ //
  296. ALuint unusedAlBufferId = 0;
  297. alGenBuffers(1, &unusedAlBufferId);
  298. alDeleteBuffers(1, &unusedAlBufferId);
  299. // ================ Workaround end ================ //
  300. _scheduler = Director::getInstance()->getScheduler();
  301. ret = true;
  302. ALOGI("OpenAL was initialized successfully!");
  303. }
  304. }while (false);
  305. return ret;
  306. }
  307. AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool)> callback)
  308. {
  309. AudioCache* audioCache = nullptr;
  310. auto it = _audioCaches.find(filePath);
  311. if (it == _audioCaches.end()) {
  312. audioCache = &_audioCaches[filePath];
  313. audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  314. unsigned int cacheId = audioCache->_id;
  315. auto isCacheDestroyed = audioCache->_isDestroyed;
  316. AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){
  317. if (*isCacheDestroyed)
  318. {
  319. ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId);
  320. audioCache->setSkipReadDataTask(true);
  321. return;
  322. }
  323. audioCache->readDataTask(cacheId);
  324. });
  325. }
  326. else {
  327. audioCache = &it->second;
  328. }
  329. if (audioCache && callback)
  330. {
  331. audioCache->addLoadCallback(callback);
  332. }
  333. return audioCache;
  334. }
  335. int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
  336. {
  337. if (s_ALDevice == nullptr) {
  338. return AudioEngine::INVALID_AUDIO_ID;
  339. }
  340. ALuint alSource = findValidSource();
  341. if (alSource == AL_INVALID)
  342. {
  343. return AudioEngine::INVALID_AUDIO_ID;
  344. }
  345. auto player = new (std::nothrow) AudioPlayer;
  346. if (player == nullptr) {
  347. return AudioEngine::INVALID_AUDIO_ID;
  348. }
  349. player->_alSource = alSource;
  350. player->_loop = loop;
  351. player->_volume = volume;
  352. auto audioCache = preload(filePath, nullptr);
  353. if (audioCache == nullptr) {
  354. delete player;
  355. return AudioEngine::INVALID_AUDIO_ID;
  356. }
  357. player->setCache(audioCache);
  358. _threadMutex.lock();
  359. _audioPlayers[_currentAudioID] = player;
  360. _threadMutex.unlock();
  361. audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID));
  362. if (_lazyInitLoop) {
  363. _lazyInitLoop = false;
  364. _scheduler->schedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this, 0.05f, false);
  365. }
  366. return _currentAudioID++;
  367. }
  368. void AudioEngineImpl::_play2d(AudioCache *cache, int audioID)
  369. {
  370. //Note: It may bn in sub thread or main thread :(
  371. if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY)
  372. {
  373. _threadMutex.lock();
  374. auto playerIt = _audioPlayers.find(audioID);
  375. if (playerIt != _audioPlayers.end() && playerIt->second->play2d()) {
  376. _scheduler->performFunctionInCocosThread([audioID](){
  377. if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) {
  378. AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
  379. }
  380. });
  381. }
  382. _threadMutex.unlock();
  383. }
  384. else
  385. {
  386. ALOGD("AudioEngineImpl::_play2d, cache was destroyed or not ready!");
  387. auto iter = _audioPlayers.find(audioID);
  388. if (iter != _audioPlayers.end())
  389. {
  390. iter->second->_removeByAudioEngine = true;
  391. }
  392. }
  393. }
  394. ALuint AudioEngineImpl::findValidSource()
  395. {
  396. ALuint sourceId = AL_INVALID;
  397. if (!_unusedSourcesPool.empty())
  398. {
  399. sourceId = _unusedSourcesPool.front();
  400. _unusedSourcesPool.pop_front();
  401. }
  402. return sourceId;
  403. }
  404. void AudioEngineImpl::setVolume(int audioID,float volume)
  405. {
  406. auto player = _audioPlayers[audioID];
  407. player->_volume = volume;
  408. if (player->_ready) {
  409. alSourcef(_audioPlayers[audioID]->_alSource, AL_GAIN, volume);
  410. auto error = alGetError();
  411. if (error != AL_NO_ERROR) {
  412. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  413. }
  414. }
  415. }
  416. void AudioEngineImpl::setLoop(int audioID, bool loop)
  417. {
  418. auto player = _audioPlayers[audioID];
  419. if (player->_ready) {
  420. if (player->_streamingSource) {
  421. player->setLoop(loop);
  422. } else {
  423. if (loop) {
  424. alSourcei(player->_alSource, AL_LOOPING, AL_TRUE);
  425. } else {
  426. alSourcei(player->_alSource, AL_LOOPING, AL_FALSE);
  427. }
  428. auto error = alGetError();
  429. if (error != AL_NO_ERROR) {
  430. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  431. }
  432. }
  433. }
  434. else {
  435. player->_loop = loop;
  436. }
  437. }
  438. bool AudioEngineImpl::pause(int audioID)
  439. {
  440. bool ret = true;
  441. alSourcePause(_audioPlayers[audioID]->_alSource);
  442. auto error = alGetError();
  443. if (error != AL_NO_ERROR) {
  444. ret = false;
  445. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  446. }
  447. return ret;
  448. }
  449. bool AudioEngineImpl::resume(int audioID)
  450. {
  451. bool ret = true;
  452. alSourcePlay(_audioPlayers[audioID]->_alSource);
  453. auto error = alGetError();
  454. if (error != AL_NO_ERROR) {
  455. ret = false;
  456. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  457. }
  458. return ret;
  459. }
  460. void AudioEngineImpl::stop(int audioID)
  461. {
  462. auto player = _audioPlayers[audioID];
  463. player->destroy();
  464. // Call 'update' method to cleanup immediately since the schedule may be cancelled without any notification.
  465. update(0.0f);
  466. }
  467. void AudioEngineImpl::stopAll()
  468. {
  469. for(auto&& player : _audioPlayers)
  470. {
  471. player.second->destroy();
  472. }
  473. // Call 'update' method to cleanup immediately since the schedule may be cancelled without any notification.
  474. update(0.0f);
  475. }
  476. float AudioEngineImpl::getDuration(int audioID)
  477. {
  478. auto player = _audioPlayers[audioID];
  479. if(player->_ready){
  480. return player->_audioCache->_duration;
  481. } else {
  482. return AudioEngine::TIME_UNKNOWN;
  483. }
  484. }
  485. float AudioEngineImpl::getCurrentTime(int audioID)
  486. {
  487. float ret = 0.0f;
  488. auto player = _audioPlayers[audioID];
  489. if(player->_ready){
  490. if (player->_streamingSource) {
  491. ret = player->getTime();
  492. } else {
  493. alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret);
  494. auto error = alGetError();
  495. if (error != AL_NO_ERROR) {
  496. ALOGE("%s, audio id:%d,error code:%x", __PRETTY_FUNCTION__,audioID,error);
  497. }
  498. }
  499. }
  500. return ret;
  501. }
  502. bool AudioEngineImpl::setCurrentTime(int audioID, float time)
  503. {
  504. bool ret = false;
  505. auto player = _audioPlayers[audioID];
  506. do {
  507. if (!player->_ready) {
  508. break;
  509. }
  510. if (player->_streamingSource) {
  511. ret = player->setTime(time);
  512. break;
  513. }
  514. else {
  515. if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames &&
  516. (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) {
  517. ALOGE("%s: audio id = %d", __PRETTY_FUNCTION__,audioID);
  518. break;
  519. }
  520. alSourcef(player->_alSource, AL_SEC_OFFSET, time);
  521. auto error = alGetError();
  522. if (error != AL_NO_ERROR) {
  523. ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
  524. }
  525. ret = true;
  526. }
  527. } while (0);
  528. return ret;
  529. }
  530. void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  531. {
  532. _audioPlayers[audioID]->_finishCallbak = callback;
  533. }
  534. void AudioEngineImpl::update(float dt)
  535. {
  536. ALint sourceState;
  537. int audioID;
  538. AudioPlayer* player;
  539. ALuint alSource;
  540. // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size());
  541. for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) {
  542. audioID = it->first;
  543. player = it->second;
  544. alSource = player->_alSource;
  545. alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState);
  546. if (player->_removeByAudioEngine)
  547. {
  548. AudioEngine::remove(audioID);
  549. _threadMutex.lock();
  550. it = _audioPlayers.erase(it);
  551. _threadMutex.unlock();
  552. delete player;
  553. _unusedSourcesPool.push_back(alSource);
  554. }
  555. else if (player->_ready && sourceState == AL_STOPPED) {
  556. std::string filePath;
  557. if (player->_finishCallbak) {
  558. auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
  559. filePath = *audioInfo.filePath;
  560. }
  561. AudioEngine::remove(audioID);
  562. _threadMutex.lock();
  563. it = _audioPlayers.erase(it);
  564. _threadMutex.unlock();
  565. if (player->_finishCallbak) {
  566. player->_finishCallbak(audioID, filePath); //FIXME: callback will delay 50ms
  567. }
  568. delete player;
  569. _unusedSourcesPool.push_back(alSource);
  570. }
  571. else{
  572. ++it;
  573. }
  574. }
  575. if(_audioPlayers.empty()){
  576. _lazyInitLoop = true;
  577. _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
  578. }
  579. }
  580. void AudioEngineImpl::uncache(const std::string &filePath)
  581. {
  582. _audioCaches.erase(filePath);
  583. }
  584. void AudioEngineImpl::uncacheAll()
  585. {
  586. _audioCaches.clear();
  587. }
  588. #endif