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