CDAudioManager.m 30 KB

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