CDAudioManager.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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. [[NSNotificationCenter defaultCenter] addObserver: self
  361. selector: NSSelectorFromString(@"handleInterruption")
  362. name: AVAudioSessionInterruptionNotification
  363. object: [AVAudioSession sharedInstance]];
  364. _mode = mode;
  365. backgroundMusicCompletionSelector = nil;
  366. _isObservingAppEvents = FALSE;
  367. _mute = NO;
  368. _resigned = NO;
  369. _interrupted = NO;
  370. enabled_ = YES;
  371. _audioSessionActive = NO;
  372. [self setMode:mode];
  373. soundEngine = [[CDSoundEngine alloc] init];
  374. //Set up audioSource channels
  375. audioSourceChannels = [[NSMutableArray alloc] init];
  376. CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init];
  377. leftChannel.backgroundMusic = YES;
  378. CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init];
  379. rightChannel.backgroundMusic = NO;
  380. [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left];
  381. [audioSourceChannels insertObject:rightChannel atIndex:kASC_Right];
  382. [leftChannel release];
  383. [rightChannel release];
  384. //Used to support legacy APIs
  385. backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL];
  386. backgroundMusic.delegate = self;
  387. //Add handler for bad al context messages, these are posted by the sound engine.
  388. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badAlContextHandler) name:kCDN_BadAlContext object:nil];
  389. }
  390. return self;
  391. }
  392. -(void) dealloc {
  393. CDLOGINFO(@"Denshion::CDAudioManager - deallocating");
  394. [self stopBackgroundMusic];
  395. [soundEngine release];
  396. [[NSNotificationCenter defaultCenter] removeObserver:self];
  397. [self audioSessionSetActive:NO];
  398. [audioSourceChannels release];
  399. [super dealloc];
  400. }
  401. /** Retrieves the audio source for the specified channel */
  402. -(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel
  403. {
  404. return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel];
  405. }
  406. /** Loads the data from the specified file path to the channel's audio source */
  407. -(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel
  408. {
  409. CDLongAudioSource *audioSource = [self audioSourceForChannel:channel];
  410. if (audioSource) {
  411. [audioSource load:filePath];
  412. }
  413. return audioSource;
  414. }
  415. -(BOOL) isBackgroundMusicPlaying {
  416. return [self.backgroundMusic isPlaying];
  417. }
  418. //NB: originally I tried using a route change listener and intended to store the current route,
  419. //however, on a 3gs running 3.1.2 no route change is generated when the user switches the
  420. //ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to
  421. //determine ringer switch state
  422. -(BOOL) isDeviceMuted {
  423. #if TARGET_IPHONE_SIMULATOR || defined(CC_TARGET_OS_TVOS)
  424. //Calling audio route stuff on the simulator causes problems
  425. return NO;
  426. #else
  427. CFStringRef newAudioRoute;
  428. UInt32 propertySize = sizeof (CFStringRef);
  429. AudioSessionGetProperty (
  430. kAudioSessionProperty_AudioRoute,
  431. &propertySize,
  432. &newAudioRoute
  433. );
  434. if (newAudioRoute == NULL) {
  435. //Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash
  436. return YES;
  437. } else {
  438. CFComparisonResult newDeviceIsMuted = CFStringCompare (
  439. newAudioRoute,
  440. (CFStringRef) @"",
  441. 0
  442. );
  443. return (newDeviceIsMuted == kCFCompareEqualTo);
  444. }
  445. #endif
  446. }
  447. #pragma mark Audio Interrupt Protocol
  448. -(BOOL) mute {
  449. return _mute;
  450. }
  451. -(void) setMute:(BOOL) muteValue {
  452. if (muteValue != _mute) {
  453. _mute = muteValue;
  454. [soundEngine setMute:muteValue];
  455. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  456. audioSource.mute = muteValue;
  457. }
  458. }
  459. }
  460. -(BOOL) enabled {
  461. return enabled_;
  462. }
  463. -(void) setEnabled:(BOOL) enabledValue {
  464. if (enabledValue != enabled_) {
  465. enabled_ = enabledValue;
  466. [soundEngine setEnabled:enabled_];
  467. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  468. audioSource.enabled = enabled_;
  469. }
  470. }
  471. }
  472. -(CDLongAudioSource*) backgroundMusic
  473. {
  474. return backgroundMusic;
  475. }
  476. //Load background music ready for playing
  477. -(void) preloadBackgroundMusic:(NSString*) filePath
  478. {
  479. [self.backgroundMusic load:filePath];
  480. }
  481. -(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop
  482. {
  483. [self.backgroundMusic load:filePath];
  484. if (loop) {
  485. [self.backgroundMusic setNumberOfLoops:-1];
  486. } else {
  487. [self.backgroundMusic setNumberOfLoops:0];
  488. }
  489. if (!willPlayBackgroundMusic || _mute) {
  490. CDLOGINFO(@"Denshion::CDAudioManager - play bgm aborted because audio is not exclusive or sound is muted");
  491. return;
  492. }
  493. [self.backgroundMusic play];
  494. }
  495. -(void) stopBackgroundMusic
  496. {
  497. [self.backgroundMusic stop];
  498. }
  499. -(void) pauseBackgroundMusic
  500. {
  501. [self.backgroundMusic pause];
  502. }
  503. -(void) resumeBackgroundMusic
  504. {
  505. if (!willPlayBackgroundMusic || _mute) {
  506. CDLOGINFO(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted");
  507. return;
  508. }
  509. if (![self.backgroundMusic paused]) {
  510. return;
  511. }
  512. [self.backgroundMusic resume];
  513. }
  514. -(void) rewindBackgroundMusic
  515. {
  516. [self.backgroundMusic rewind];
  517. }
  518. -(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector {
  519. backgroundMusicCompletionListener = listener;
  520. backgroundMusicCompletionSelector = selector;
  521. }
  522. /*
  523. * Call this method to have the audio manager automatically handle application resign and
  524. * become active. Pass a tAudioManagerResignBehavior to indicate the desired behavior
  525. * for resigning and becoming active again.
  526. *
  527. * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive
  528. * methods are automatically called, otherwise you must call them yourself at the appropriate time.
  529. *
  530. * Based on idea of Dominique Bongard
  531. */
  532. -(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle {
  533. if (!_isObservingAppEvents && autoHandle) {
  534. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil];
  535. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:@"UIApplicationDidBecomeActiveNotification" object:nil];
  536. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:@"UIApplicationWillTerminateNotification" object:nil];
  537. _isObservingAppEvents = TRUE;
  538. }
  539. _resignBehavior = resignBehavior;
  540. }
  541. - (void) applicationWillResignActive {
  542. _resigned = YES;
  543. //Set the audio session to one that allows sharing so that other audio won't be clobbered on resume
  544. [self audioSessionSetCategory:AVAudioSessionCategoryAmbient];
  545. switch (_resignBehavior) {
  546. case kAMRBStopPlay:
  547. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  548. if (!audioSource->systemPaused) {
  549. if (audioSource.isPlaying) {
  550. audioSource->systemPaused = YES;
  551. audioSource->systemPauseLocation = audioSource.audioSourcePlayer.currentTime;
  552. [audioSource pause];
  553. } else {
  554. //Music is either paused or stopped, if it is paused it will be restarted
  555. //by OS so we will stop it.
  556. audioSource->systemPaused = NO;
  557. [audioSource stop];
  558. }
  559. }
  560. }
  561. break;
  562. case kAMRBStop:
  563. //Stop music regardless of whether it is playing or not because if it was paused
  564. //then the OS would resume it
  565. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  566. [audioSource stop];
  567. }
  568. default:
  569. break;
  570. }
  571. CDLOGINFO(@"Denshion::CDAudioManager - handled resign active");
  572. }
  573. //Called when application resigns active only if setResignBehavior has been called
  574. - (void) applicationWillResignActive:(NSNotification *) notification
  575. {
  576. [self applicationWillResignActive];
  577. }
  578. - (void) applicationDidBecomeActive {
  579. if (_resigned) {
  580. _resigned = NO;
  581. //Reset the mode incase something changed with audio while we were inactive
  582. [self setMode:_mode];
  583. switch (_resignBehavior) {
  584. case kAMRBStopPlay:
  585. //Music had been stopped but stop maintains current time
  586. //so playing again will continue from where music was before resign active.
  587. //We check if music can be played because while we were inactive the user might have
  588. //done something that should force music to not play such as starting a track in the iPod
  589. if (self.willPlayBackgroundMusic) {
  590. for( CDLongAudioSource *audioSource in audioSourceChannels) {
  591. if (audioSource->systemPaused) {
  592. [audioSource resume];
  593. audioSource->systemPaused = NO;
  594. }
  595. }
  596. }
  597. break;
  598. default:
  599. break;
  600. }
  601. CDLOGINFO(@"Denshion::CDAudioManager - audio manager handled become active");
  602. }
  603. }
  604. //Called when application becomes active only if setResignBehavior has been called
  605. - (void) applicationDidBecomeActive:(NSNotification *) notification
  606. {
  607. [self applicationDidBecomeActive];
  608. }
  609. //Called when application terminates only if setResignBehavior has been called
  610. - (void) applicationWillTerminate:(NSNotification *) notification
  611. {
  612. CDLOGINFO(@"Denshion::CDAudioManager - audio manager handling terminate");
  613. [self stopBackgroundMusic];
  614. }
  615. /** The audio source completed playing */
  616. - (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource {
  617. CDLOGINFO(@"Denshion::CDAudioManager - audio manager got told background music finished");
  618. if (backgroundMusicCompletionSelector != nil) {
  619. [backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector];
  620. }
  621. }
  622. - (void) handleInterruption:(NSNotification*) notification {
  623. if (notification.name != AVAudioSessionInterruptionNotification ||
  624. notification.userInfo == nil)
  625. return;
  626. NSDictionary *interuptionDict = notification.userInfo;
  627. NSInteger interuptionType = [[interuptionDict valueForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  628. // decide what to do based on interruption type here...
  629. switch (interuptionType) {
  630. case AVAudioSessionInterruptionTypeBegan:
  631. [self audioSessionInterrupted];
  632. break;
  633. case AVAudioSessionInterruptionTypeEnded:
  634. [self audioSessionResumed];
  635. break;
  636. default:
  637. NSLog(@"Audio Session Interruption Notification case default.");
  638. break;
  639. }
  640. }
  641. -(void)audioSessionInterrupted
  642. {
  643. if (!_interrupted) {
  644. CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted");
  645. _interrupted = YES;
  646. // Deactivate the current audio session
  647. [self audioSessionSetActive:NO];
  648. if (alcGetCurrentContext() != NULL) {
  649. CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL");
  650. ALenum error = AL_NO_ERROR;
  651. // set the current context to NULL will 'shutdown' openAL
  652. alcMakeContextCurrent(NULL);
  653. if((error = alGetError()) != AL_NO_ERROR) {
  654. CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error);
  655. }
  656. #pragma unused(error)
  657. }
  658. }
  659. }
  660. -(void)audioSessionResumed
  661. {
  662. if (_interrupted) {
  663. CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed");
  664. _interrupted = NO;
  665. BOOL activationResult = NO;
  666. // Reactivate the current audio session
  667. activationResult = [self audioSessionSetActive:YES];
  668. //This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if
  669. //task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the
  670. //iPhone and then hang up after two rings (timing may vary ;))
  671. //Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is
  672. //limited.
  673. if (!activationResult) {
  674. CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle");
  675. int activateCount = 0;
  676. while (!activationResult && activateCount < 10) {
  677. [NSThread sleepForTimeInterval:0.5];
  678. activationResult = [self audioSessionSetActive:YES];
  679. activateCount++;
  680. CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult);
  681. }
  682. }
  683. if (alcGetCurrentContext() == NULL) {
  684. CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context");
  685. ALenum error = AL_NO_ERROR;
  686. // Restore open al context
  687. alcMakeContextCurrent([soundEngine openALContext]);
  688. if((error = alGetError()) != AL_NO_ERROR) {
  689. CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error);
  690. }
  691. #pragma unused(error)
  692. }
  693. }
  694. }
  695. +(void) end {
  696. [sharedManager release];
  697. sharedManager = nil;
  698. }
  699. @end
  700. ///////////////////////////////////////////////////////////////////////////////////////
  701. @implementation CDLongAudioSourceFader
  702. -(void) _setTargetProperty:(float) newVal {
  703. ((CDLongAudioSource*)target).volume = newVal;
  704. }
  705. -(float) _getTargetProperty {
  706. return ((CDLongAudioSource*)target).volume;
  707. }
  708. -(void) _stopTarget {
  709. //Pause instead of stop as stop releases resources and causes problems in the simulator
  710. [((CDLongAudioSource*)target) pause];
  711. }
  712. -(Class) _allowableType {
  713. return [CDLongAudioSource class];
  714. }
  715. @end
  716. ///////////////////////////////////////////////////////////////////////////////////////
  717. @implementation CDBufferManager
  718. -(id) initWithEngine:(CDSoundEngine *) theSoundEngine {
  719. if ((self = [super init])) {
  720. soundEngine = theSoundEngine;
  721. loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START];
  722. freedBuffers = [[NSMutableArray alloc] init];
  723. nextBufferId = 0;
  724. }
  725. return self;
  726. }
  727. -(void) dealloc {
  728. [loadedBuffers release];
  729. [freedBuffers release];
  730. [super dealloc];
  731. }
  732. -(int) bufferForFile:(NSString*) filePath create:(BOOL) create {
  733. NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath];
  734. if(soundId == nil)
  735. {
  736. if (create) {
  737. NSNumber* bufferId = nil;
  738. //First try to get a buffer from the free buffers
  739. if ([freedBuffers count] > 0) {
  740. bufferId = [[[freedBuffers lastObject] retain] autorelease];
  741. [freedBuffers removeLastObject];
  742. CDLOGINFO(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]);
  743. } else {
  744. bufferId = [[NSNumber alloc] initWithInt:nextBufferId];
  745. [bufferId autorelease];
  746. CDLOGINFO(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]);
  747. nextBufferId++;
  748. }
  749. if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) {
  750. //File successfully loaded
  751. CDLOGINFO(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath);
  752. [loadedBuffers setObject:bufferId forKey:filePath];
  753. return [bufferId intValue];
  754. } else {
  755. //File didn't load, put buffer id on free list
  756. [freedBuffers addObject:bufferId];
  757. return kCDNoBuffer;
  758. }
  759. } else {
  760. //No matching buffer was found
  761. return kCDNoBuffer;
  762. }
  763. } else {
  764. return [soundId intValue];
  765. }
  766. }
  767. -(void) releaseBufferForFile:(NSString *) filePath {
  768. int bufferId = [self bufferForFile:filePath create:NO];
  769. if (bufferId != kCDNoBuffer) {
  770. [soundEngine unloadBuffer:bufferId];
  771. [loadedBuffers removeObjectForKey:filePath];
  772. NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId];
  773. [freedBufferId autorelease];
  774. [freedBuffers addObject:freedBufferId];
  775. }
  776. }
  777. @end