CDAudioManager.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /*
  2. Copyright (c) 2010 Steve Oldmeadow
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. $Id$
  19. */
  20. #import "audio/ios/CDAudioManager.h"
  21. NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
  22. //NSOperation object used to asynchronously initialise
  23. @implementation CDAsynchInitialiser
  24. -(void) main {
  25. [super main];
  26. [CDAudioManager sharedManager];
  27. }
  28. @end
  29. @implementation CDLongAudioSource
  30. @synthesize audioSourcePlayer, audioSourceFilePath, delegate, backgroundMusic, paused;
  31. -(id) init {
  32. if ((self = [super init])) {
  33. state = kLAS_Init;
  34. volume = 1.0f;
  35. mute = NO;
  36. enabled_ = YES;
  37. paused = NO;
  38. stopped = NO;
  39. }
  40. return self;
  41. }
  42. -(void) dealloc {
  43. CDLOGINFO(@"Denshion::CDLongAudioSource - deallocating %@", self);
  44. [audioSourcePlayer release];
  45. [audioSourceFilePath release];
  46. [super dealloc];
  47. }
  48. -(void) load:(NSString*) filePath {
  49. //We have already loaded a file previously, check if we are being asked to load the same file
  50. if (state == kLAS_Init || ![filePath isEqualToString:audioSourceFilePath]) {
  51. CDLOGINFO(@"Denshion::CDLongAudioSource - Loading new audio source %@",filePath);
  52. //New file
  53. if (state != kLAS_Init) {
  54. [audioSourceFilePath release];//Release old file path
  55. [audioSourcePlayer release];//Release old AVAudioPlayer, they can't be reused
  56. }
  57. audioSourceFilePath = [filePath copy];
  58. NSError *error = nil;
  59. NSString *path = [CDUtilities fullPathFromRelativePath:audioSourceFilePath];
  60. audioSourcePlayer = [(AVAudioPlayer*)[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
  61. if (error == nil) {
  62. [audioSourcePlayer prepareToPlay];
  63. audioSourcePlayer.delegate = self;
  64. if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceFileDidChange:)]) {
  65. //Tell our delegate the file has changed
  66. [delegate cdAudioSourceFileDidChange:self];
  67. }
  68. } else {
  69. CDLOG(@"Denshion::CDLongAudioSource - Error initialising audio player: %@",error);
  70. }
  71. } else {
  72. //Same file - just return it to a consistent state
  73. [self pause];
  74. [self rewind];
  75. }
  76. audioSourcePlayer.volume = volume;
  77. audioSourcePlayer.numberOfLoops = numberOfLoops;
  78. state = kLAS_Loaded;
  79. }
  80. -(void) play {
  81. if (enabled_) {
  82. systemPaused = NO;
  83. paused = NO;
  84. stopped = NO;
  85. [audioSourcePlayer play];
  86. } else {
  87. CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled");
  88. }
  89. }
  90. -(void) stop {
  91. paused = NO;
  92. stopped = YES;
  93. [audioSourcePlayer stop];
  94. }
  95. -(void) pause {
  96. paused = YES;
  97. [audioSourcePlayer pause];
  98. }
  99. -(void) rewind {
  100. paused = NO;
  101. [audioSourcePlayer setCurrentTime:0];
  102. [audioSourcePlayer play];
  103. stopped = NO;
  104. }
  105. -(void) resume {
  106. if (!stopped) {
  107. paused = NO;
  108. [audioSourcePlayer play];
  109. }
  110. }
  111. -(BOOL) isPlaying {
  112. if (state != kLAS_Init) {
  113. return [audioSourcePlayer isPlaying];
  114. } else {
  115. return NO;
  116. }
  117. }
  118. -(void) setVolume:(float) newVolume
  119. {
  120. volume = newVolume;
  121. if (state != kLAS_Init && !mute) {
  122. audioSourcePlayer.volume = newVolume;
  123. }
  124. }
  125. -(float) volume
  126. {
  127. return volume;
  128. }
  129. #pragma mark Audio Interrupt Protocol
  130. -(BOOL) mute
  131. {
  132. return mute;
  133. }
  134. -(void) setMute:(BOOL) muteValue
  135. {
  136. if (mute != muteValue) {
  137. if (mute) {
  138. //Turn sound back on
  139. audioSourcePlayer.volume = volume;
  140. } else {
  141. audioSourcePlayer.volume = 0.0f;
  142. }
  143. mute = muteValue;
  144. }
  145. }
  146. -(BOOL) enabled
  147. {
  148. return enabled_;
  149. }
  150. -(void) setEnabled:(BOOL)enabledValue
  151. {
  152. if (enabledValue != enabled_) {
  153. enabled_ = enabledValue;
  154. if (!enabled_) {
  155. //"Stop" the sounds
  156. [self pause];
  157. [self rewind];
  158. }
  159. }
  160. }
  161. -(NSInteger) numberOfLoops {
  162. return numberOfLoops;
  163. }
  164. -(void) setNumberOfLoops:(NSInteger) loopCount
  165. {
  166. audioSourcePlayer.numberOfLoops = loopCount;
  167. numberOfLoops = loopCount;
  168. }
  169. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
  170. CDLOGINFO(@"Denshion::CDLongAudioSource - audio player finished");
  171. #if TARGET_IPHONE_SIMULATOR
  172. CDLOGINFO(@"Denshion::CDLongAudioSource - workaround for OpenAL clobbered audio issue");
  173. //This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is
  174. //that OpenAL audio playback is clobbered when an AVAudioPlayer stops. Workaround
  175. //is to keep the player playing on an endless loop with 0 volume and then when
  176. //it is played again reset the volume and set loop count appropriately.
  177. //NB: this workaround is not foolproof but it is good enough for most situations.
  178. player.numberOfLoops = -1;
  179. player.volume = 0;
  180. [player play];
  181. #endif
  182. if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceDidFinishPlaying:)]) {
  183. [delegate cdAudioSourceDidFinishPlaying:self];
  184. }
  185. }
  186. -(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
  187. CDLOGINFO(@"Denshion::CDLongAudioSource - audio player interrupted");
  188. }
  189. -(void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
  190. CDLOGINFO(@"Denshion::CDLongAudioSource - audio player resumed");
  191. if (self.backgroundMusic) {
  192. //Check if background music can play as rules may have changed during
  193. //the interruption. This is to address a specific issue in 4.x when
  194. //fast task switching
  195. if([CDAudioManager sharedManager].willPlayBackgroundMusic) {
  196. [player play];
  197. }
  198. } else {
  199. [player play];
  200. }
  201. }
  202. @end
  203. @interface CDAudioManager (PrivateMethods)
  204. -(BOOL) audioSessionSetActive:(BOOL) active;
  205. -(BOOL) audioSessionSetCategory:(NSString*) category;
  206. -(void) badAlContextHandler;
  207. @end
  208. @implementation CDAudioManager
  209. #define BACKGROUND_MUSIC_CHANNEL kASC_Left
  210. @synthesize soundEngine, willPlayBackgroundMusic;
  211. static CDAudioManager *sharedManager;
  212. static tAudioManagerState _sharedManagerState = kAMStateUninitialised;
  213. static tAudioManagerMode configuredMode;
  214. static BOOL configured = FALSE;
  215. -(BOOL) audioSessionSetActive:(BOOL) active {
  216. NSError *activationError = nil;
  217. if ([[AVAudioSession sharedInstance] setActive:active error:&activationError]) {
  218. _audioSessionActive = active;
  219. CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active);
  220. return YES;
  221. } else {
  222. //Failed
  223. CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError);
  224. return NO;
  225. }
  226. }
  227. -(BOOL) audioSessionSetCategory:(NSString*) category {
  228. NSError *categoryError = nil;
  229. if ([[AVAudioSession sharedInstance] setCategory:category error:&categoryError]) {
  230. CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category);
  231. return YES;
  232. } else {
  233. //Failed
  234. CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError);
  235. return NO;
  236. }
  237. }
  238. // Init
  239. + (CDAudioManager *) sharedManager
  240. {
  241. @synchronized(self) {
  242. if (!sharedManager) {
  243. if (!configured) {
  244. //Set defaults here
  245. configuredMode = kAMM_FxPlusMusicIfNoOtherAudio;
  246. }
  247. sharedManager = [[CDAudioManager alloc] init:configuredMode];
  248. _sharedManagerState = kAMStateInitialised;//This is only really relevant when using asynchronous initialisation
  249. [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AudioManagerInitialised object:nil];
  250. }
  251. }
  252. return sharedManager;
  253. }
  254. + (tAudioManagerState) sharedManagerState {
  255. return _sharedManagerState;
  256. }
  257. /**
  258. * Call this to set up audio manager asynchronously. Initialisation is finished when sharedManagerState == kAMStateInitialised
  259. */
  260. + (void) initAsynchronously: (tAudioManagerMode) mode {
  261. @synchronized(self) {
  262. if (_sharedManagerState == kAMStateUninitialised) {
  263. _sharedManagerState = kAMStateInitialising;
  264. [CDAudioManager configure:mode];
  265. CDAsynchInitialiser *initOp = [[[CDAsynchInitialiser alloc] init] autorelease];
  266. NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease];
  267. [opQ addOperation:initOp];
  268. }
  269. }
  270. }
  271. + (id) alloc
  272. {
  273. @synchronized(self) {
  274. NSAssert(sharedManager == nil, @"Attempted to allocate a second instance of a singleton.");
  275. return [super alloc];
  276. }
  277. return nil;
  278. }
  279. /*
  280. * Call this method before accessing the shared manager in order to configure the shared audio manager
  281. */
  282. + (void) configure: (tAudioManagerMode) mode {
  283. configuredMode = mode;
  284. configured = TRUE;
  285. }
  286. -(BOOL) isOtherAudioPlaying
  287. {
  288. // AudioSessionGetProperty removed from tvOS 9.1
  289. #if defined(CC_TARGET_OS_TVOS)
  290. return false;
  291. #else
  292. UInt32 isPlaying = 0;
  293. UInt32 varSize = sizeof(isPlaying);
  294. AudioSessionGetProperty (kAudioSessionProperty_OtherAudioIsPlaying, &varSize, &isPlaying);
  295. return (isPlaying != 0);
  296. #endif
  297. }
  298. -(void) setMode:(tAudioManagerMode) mode {
  299. _mode = mode;
  300. switch (_mode) {
  301. case kAMM_FxOnly:
  302. //Share audio with other app
  303. CDLOGINFO(@"Denshion::CDAudioManager - Audio will be shared");
  304. //_audioSessionCategory = kAudioSessionCategory_AmbientSound;
  305. _audioSessionCategory = AVAudioSessionCategoryAmbient;
  306. willPlayBackgroundMusic = NO;
  307. break;
  308. case kAMM_FxPlusMusic:
  309. //Use audio exclusively - if other audio is playing it will be stopped
  310. CDLOGINFO(@"Denshion::CDAudioManager - Audio will be exclusive");
  311. //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound;
  312. _audioSessionCategory = AVAudioSessionCategorySoloAmbient;
  313. willPlayBackgroundMusic = YES;
  314. break;
  315. case kAMM_MediaPlayback:
  316. //Use audio exclusively, ignore mute switch and sleep
  317. CDLOGINFO(@"Denshion::CDAudioManager - Media playback mode, audio will be exclusive");
  318. //_audioSessionCategory = kAudioSessionCategory_MediaPlayback;
  319. _audioSessionCategory = AVAudioSessionCategoryPlayback;
  320. willPlayBackgroundMusic = YES;
  321. break;
  322. case kAMM_PlayAndRecord:
  323. //Use audio exclusively, ignore mute switch and sleep, has inputs and outputs
  324. CDLOGINFO(@"Denshion::CDAudioManager - Play and record mode, audio will be exclusive");
  325. //_audioSessionCategory = kAudioSessionCategory_PlayAndRecord;
  326. _audioSessionCategory = AVAudioSessionCategoryPlayAndRecord;
  327. willPlayBackgroundMusic = YES;
  328. break;
  329. default:
  330. //kAudioManagerFxPlusMusicIfNoOtherAudio
  331. if ([self isOtherAudioPlaying]) {
  332. CDLOGINFO(@"Denshion::CDAudioManager - Other audio is playing audio will be shared");
  333. //_audioSessionCategory = kAudioSessionCategory_AmbientSound;
  334. _audioSessionCategory = AVAudioSessionCategoryAmbient;
  335. willPlayBackgroundMusic = NO;
  336. } else {
  337. CDLOGINFO(@"Denshion::CDAudioManager - Other audio is not playing audio will be exclusive");
  338. //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound;
  339. _audioSessionCategory = AVAudioSessionCategorySoloAmbient;
  340. willPlayBackgroundMusic = YES;
  341. }
  342. break;
  343. }
  344. [self audioSessionSetCategory:_audioSessionCategory];
  345. }
  346. /**
  347. * This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the
  348. * audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following
  349. * standard practices. If we detect this situation then we will attempt to resume the audio session ourselves.
  350. * Known triggers: lock the device then unlock it (iOS 4.2 gm), playback a song using MPMediaPlayer (iOS 4.0)
  351. */
  352. - (void) badAlContextHandler {
  353. if (_interrupted && alcGetCurrentContext() == NULL) {
  354. CDLOG(@"Denshion::CDAudioManager - bad OpenAL context detected, attempting to resume audio session");
  355. [self audioSessionResumed];
  356. }
  357. }
  358. - (id) init: (tAudioManagerMode) mode {
  359. if ((self = [super init])) {
  360. // 'delegate' not supported on tvOS
  361. #if !defined(CC_TARGET_OS_TVOS)
  362. //Initialise the audio session
  363. AVAudioSession* session = [AVAudioSession sharedInstance];
  364. session.delegate = self;
  365. #endif
  366. _mode = mode;
  367. backgroundMusicCompletionSelector = nil;
  368. _isObservingAppEvents = FALSE;
  369. _mute = NO;
  370. _resigned = NO;
  371. _interrupted = NO;
  372. enabled_ = YES;
  373. _audioSessionActive = NO;
  374. [self setMode:mode];
  375. soundEngine = [[CDSoundEngine alloc] init];
  376. //Set up audioSource channels
  377. audioSourceChannels = [[NSMutableArray alloc] init];
  378. CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init];
  379. leftChannel.backgroundMusic = YES;
  380. CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init];
  381. rightChannel.backgroundMusic = NO;
  382. [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left];
  383. [audioSourceChannels insertObject:rightChannel atIndex:kASC_Right];
  384. [leftChannel release];
  385. [rightChannel release];
  386. //Used to support legacy APIs
  387. backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL];
  388. backgroundMusic.delegate = self;
  389. //Add handler for bad al context messages, these are posted by the sound engine.
  390. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badAlContextHandler) name:kCDN_BadAlContext object:nil];
  391. }
  392. return self;
  393. }
  394. -(void) dealloc {
  395. CDLOGINFO(@"Denshion::CDAudioManager - deallocating");
  396. [self stopBackgroundMusic];
  397. [soundEngine release];
  398. [[NSNotificationCenter defaultCenter] removeObserver:self];
  399. [self audioSessionSetActive:NO];
  400. [audioSourceChannels release];
  401. [super dealloc];
  402. }
  403. /** Retrieves the audio source for the specified channel */
  404. -(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel
  405. {
  406. return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel];
  407. }
  408. /** Loads the data from the specified file path to the channel's audio source */
  409. -(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel
  410. {
  411. CDLongAudioSource *audioSource = [self audioSourceForChannel:channel];
  412. if (audioSource) {
  413. [audioSource load:filePath];
  414. }
  415. return audioSource;
  416. }
  417. -(BOOL) isBackgroundMusicPlaying {
  418. return [self.backgroundMusic isPlaying];
  419. }
  420. //NB: originally I tried using a route change listener and intended to store the current route,
  421. //however, on a 3gs running 3.1.2 no route change is generated when the user switches the
  422. //ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to
  423. //determine ringer switch state
  424. -(BOOL) isDeviceMuted {
  425. #if TARGET_IPHONE_SIMULATOR || defined(CC_TARGET_OS_TVOS)
  426. //Calling audio route stuff on the simulator causes problems
  427. return NO;
  428. #else
  429. CFStringRef newAudioRoute;
  430. UInt32 propertySize = sizeof (CFStringRef);
  431. AudioSessionGetProperty (
  432. kAudioSessionProperty_AudioRoute,
  433. &propertySize,
  434. &newAudioRoute
  435. );
  436. if (newAudioRoute == NULL) {
  437. //Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash
  438. return YES;
  439. } else {
  440. CFComparisonResult newDeviceIsMuted = CFStringCompare (
  441. newAudioRoute,
  442. (CFStringRef) @"",
  443. 0
  444. );
  445. return (newDeviceIsMuted == kCFCompareEqualTo);
  446. }
  447. #endif
  448. }
  449. #pragma mark Audio Interrupt Protocol
  450. -(BOOL) mute {
  451. return _mute;
  452. }
  453. -(void) setMute:(BOOL) muteValue {
  454. if (muteValue != _mute) {
  455. _mute = muteValue;
  456. [soundEngine setMute:muteValue];
  457. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  458. audioSource.mute = muteValue;
  459. }
  460. }
  461. }
  462. -(BOOL) enabled {
  463. return enabled_;
  464. }
  465. -(void) setEnabled:(BOOL) enabledValue {
  466. if (enabledValue != enabled_) {
  467. enabled_ = enabledValue;
  468. [soundEngine setEnabled:enabled_];
  469. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  470. audioSource.enabled = enabled_;
  471. }
  472. }
  473. }
  474. -(CDLongAudioSource*) backgroundMusic
  475. {
  476. return backgroundMusic;
  477. }
  478. //Load background music ready for playing
  479. -(void) preloadBackgroundMusic:(NSString*) filePath
  480. {
  481. [self.backgroundMusic load:filePath];
  482. }
  483. -(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop
  484. {
  485. [self.backgroundMusic load:filePath];
  486. if (loop) {
  487. [self.backgroundMusic setNumberOfLoops:-1];
  488. } else {
  489. [self.backgroundMusic setNumberOfLoops:0];
  490. }
  491. if (!willPlayBackgroundMusic || _mute) {
  492. CDLOGINFO(@"Denshion::CDAudioManager - play bgm aborted because audio is not exclusive or sound is muted");
  493. return;
  494. }
  495. [self.backgroundMusic play];
  496. }
  497. -(void) stopBackgroundMusic
  498. {
  499. [self.backgroundMusic stop];
  500. }
  501. -(void) pauseBackgroundMusic
  502. {
  503. [self.backgroundMusic pause];
  504. }
  505. -(void) resumeBackgroundMusic
  506. {
  507. if (!willPlayBackgroundMusic || _mute) {
  508. CDLOGINFO(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted");
  509. return;
  510. }
  511. if (![self.backgroundMusic paused]) {
  512. return;
  513. }
  514. [self.backgroundMusic resume];
  515. }
  516. -(void) rewindBackgroundMusic
  517. {
  518. [self.backgroundMusic rewind];
  519. }
  520. -(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector {
  521. backgroundMusicCompletionListener = listener;
  522. backgroundMusicCompletionSelector = selector;
  523. }
  524. /*
  525. * Call this method to have the audio manager automatically handle application resign and
  526. * become active. Pass a tAudioManagerResignBehavior to indicate the desired behavior
  527. * for resigning and becoming active again.
  528. *
  529. * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive
  530. * methods are automatically called, otherwise you must call them yourself at the appropriate time.
  531. *
  532. * Based on idea of Dominique Bongard
  533. */
  534. -(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle {
  535. if (!_isObservingAppEvents && autoHandle) {
  536. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil];
  537. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:@"UIApplicationDidBecomeActiveNotification" object:nil];
  538. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:@"UIApplicationWillTerminateNotification" object:nil];
  539. _isObservingAppEvents = TRUE;
  540. }
  541. _resignBehavior = resignBehavior;
  542. }
  543. - (void) applicationWillResignActive {
  544. _resigned = YES;
  545. //Set the audio session to one that allows sharing so that other audio won't be clobbered on resume
  546. [self audioSessionSetCategory:AVAudioSessionCategoryAmbient];
  547. switch (_resignBehavior) {
  548. case kAMRBStopPlay:
  549. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  550. if (!audioSource->systemPaused) {
  551. if (audioSource.isPlaying) {
  552. audioSource->systemPaused = YES;
  553. audioSource->systemPauseLocation = audioSource.audioSourcePlayer.currentTime;
  554. [audioSource pause];
  555. } else {
  556. //Music is either paused or stopped, if it is paused it will be restarted
  557. //by OS so we will stop it.
  558. audioSource->systemPaused = NO;
  559. [audioSource stop];
  560. }
  561. }
  562. }
  563. break;
  564. case kAMRBStop:
  565. //Stop music regardless of whether it is playing or not because if it was paused
  566. //then the OS would resume it
  567. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  568. [audioSource stop];
  569. }
  570. default:
  571. break;
  572. }
  573. CDLOGINFO(@"Denshion::CDAudioManager - handled resign active");
  574. }
  575. //Called when application resigns active only if setResignBehavior has been called
  576. - (void) applicationWillResignActive:(NSNotification *) notification
  577. {
  578. [self applicationWillResignActive];
  579. }
  580. - (void) applicationDidBecomeActive {
  581. if (_resigned) {
  582. _resigned = NO;
  583. //Reset the mode incase something changed with audio while we were inactive
  584. [self setMode:_mode];
  585. switch (_resignBehavior) {
  586. case kAMRBStopPlay:
  587. //Music had been stopped but stop maintains current time
  588. //so playing again will continue from where music was before resign active.
  589. //We check if music can be played because while we were inactive the user might have
  590. //done something that should force music to not play such as starting a track in the iPod
  591. if (self.willPlayBackgroundMusic) {
  592. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  593. if (audioSource->systemPaused) {
  594. [audioSource resume];
  595. audioSource->systemPaused = NO;
  596. }
  597. }
  598. }
  599. break;
  600. default:
  601. break;
  602. }
  603. CDLOGINFO(@"Denshion::CDAudioManager - audio manager handled become active");
  604. }
  605. }
  606. //Called when application becomes active only if setResignBehavior has been called
  607. - (void) applicationDidBecomeActive:(NSNotification *) notification
  608. {
  609. [self applicationDidBecomeActive];
  610. }
  611. //Called when application terminates only if setResignBehavior has been called
  612. - (void) applicationWillTerminate:(NSNotification *) notification
  613. {
  614. CDLOGINFO(@"Denshion::CDAudioManager - audio manager handling terminate");
  615. [self stopBackgroundMusic];
  616. }
  617. /** The audio source completed playing */
  618. - (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource {
  619. CDLOGINFO(@"Denshion::CDAudioManager - audio manager got told background music finished");
  620. if (backgroundMusicCompletionSelector != nil) {
  621. [backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector];
  622. }
  623. }
  624. -(void) beginInterruption {
  625. CDLOGINFO(@"Denshion::CDAudioManager - begin interruption");
  626. [self audioSessionInterrupted];
  627. }
  628. -(void) endInterruption {
  629. CDLOGINFO(@"Denshion::CDAudioManager - end interruption");
  630. [self audioSessionResumed];
  631. }
  632. #if __CC_PLATFORM_IOS >= 40000
  633. -(void) endInterruptionWithFlags:(NSUInteger)flags {
  634. CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags);
  635. if (flags == AVAudioSessionInterruptionFlags_ShouldResume) {
  636. [self audioSessionResumed];
  637. }
  638. }
  639. #endif
  640. -(void)audioSessionInterrupted
  641. {
  642. if (!_interrupted) {
  643. CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted");
  644. _interrupted = YES;
  645. // Deactivate the current audio session
  646. [self audioSessionSetActive:NO];
  647. if (alcGetCurrentContext() != NULL) {
  648. CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL");
  649. ALenum error = AL_NO_ERROR;
  650. // set the current context to NULL will 'shutdown' openAL
  651. alcMakeContextCurrent(NULL);
  652. if((error = alGetError()) != AL_NO_ERROR) {
  653. CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error);
  654. }
  655. #pragma unused(error)
  656. }
  657. }
  658. }
  659. -(void)audioSessionResumed
  660. {
  661. if (_interrupted) {
  662. CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed");
  663. _interrupted = NO;
  664. BOOL activationResult = NO;
  665. // Reactivate the current audio session
  666. activationResult = [self audioSessionSetActive:YES];
  667. //This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if
  668. //task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the
  669. //iPhone and then hang up after two rings (timing may vary ;))
  670. //Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is
  671. //limited.
  672. if (!activationResult) {
  673. CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle");
  674. int activateCount = 0;
  675. while (!activationResult && activateCount < 10) {
  676. [NSThread sleepForTimeInterval:0.5];
  677. activationResult = [self audioSessionSetActive:YES];
  678. activateCount++;
  679. CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult);
  680. }
  681. }
  682. if (alcGetCurrentContext() == NULL) {
  683. CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context");
  684. ALenum error = AL_NO_ERROR;
  685. // Restore open al context
  686. alcMakeContextCurrent([soundEngine openALContext]);
  687. if((error = alGetError()) != AL_NO_ERROR) {
  688. CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error);
  689. }
  690. #pragma unused(error)
  691. }
  692. }
  693. }
  694. +(void) end {
  695. [sharedManager release];
  696. sharedManager = nil;
  697. }
  698. @end
  699. ///////////////////////////////////////////////////////////////////////////////////////
  700. @implementation CDLongAudioSourceFader
  701. -(void) _setTargetProperty:(float) newVal {
  702. ((CDLongAudioSource*)target).volume = newVal;
  703. }
  704. -(float) _getTargetProperty {
  705. return ((CDLongAudioSource*)target).volume;
  706. }
  707. -(void) _stopTarget {
  708. //Pause instead of stop as stop releases resources and causes problems in the simulator
  709. [((CDLongAudioSource*)target) pause];
  710. }
  711. -(Class) _allowableType {
  712. return [CDLongAudioSource class];
  713. }
  714. @end
  715. ///////////////////////////////////////////////////////////////////////////////////////
  716. @implementation CDBufferManager
  717. -(id) initWithEngine:(CDSoundEngine *) theSoundEngine {
  718. if ((self = [super init])) {
  719. soundEngine = theSoundEngine;
  720. loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START];
  721. freedBuffers = [[NSMutableArray alloc] init];
  722. nextBufferId = 0;
  723. }
  724. return self;
  725. }
  726. -(void) dealloc {
  727. [loadedBuffers release];
  728. [freedBuffers release];
  729. [super dealloc];
  730. }
  731. -(int) bufferForFile:(NSString*) filePath create:(BOOL) create {
  732. NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath];
  733. if(soundId == nil)
  734. {
  735. if (create) {
  736. NSNumber* bufferId = nil;
  737. //First try to get a buffer from the free buffers
  738. if ([freedBuffers count] > 0) {
  739. bufferId = [[[freedBuffers lastObject] retain] autorelease];
  740. [freedBuffers removeLastObject];
  741. CDLOGINFO(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]);
  742. } else {
  743. bufferId = [[NSNumber alloc] initWithInt:nextBufferId];
  744. [bufferId autorelease];
  745. CDLOGINFO(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]);
  746. nextBufferId++;
  747. }
  748. if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) {
  749. //File successfully loaded
  750. CDLOGINFO(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath);
  751. [loadedBuffers setObject:bufferId forKey:filePath];
  752. return [bufferId intValue];
  753. } else {
  754. //File didn't load, put buffer id on free list
  755. [freedBuffers addObject:bufferId];
  756. return kCDNoBuffer;
  757. }
  758. } else {
  759. //No matching buffer was found
  760. return kCDNoBuffer;
  761. }
  762. } else {
  763. return [soundId intValue];
  764. }
  765. }
  766. -(void) releaseBufferForFile:(NSString *) filePath {
  767. int bufferId = [self bufferForFile:filePath create:NO];
  768. if (bufferId != kCDNoBuffer) {
  769. [soundEngine unloadBuffer:bufferId];
  770. [loadedBuffers removeObjectForKey:filePath];
  771. NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId];
  772. [freedBufferId autorelease];
  773. [freedBuffers addObject:freedBufferId];
  774. }
  775. }
  776. @end