cocos2d-x 3.x BGM handling with iTunes music play
from: http://qiita.com/noir/items/83e8ad09cebb57a32224
Basic approach is to set AudioSession category to AVAudioSessionCategoryAmbient and check otherAudioPlaying property.
- Write a bridge class between Objective-C and C++: e.g. GameUtil.h, GameUtil.mm
- Create following methods in GameUtil class
- setCategoryAmbient method to set Ambient category
- isOtherAudioPlaying method to get otherAudioPlaying property
- in the method of didFinishLaunching in AppDelegate.cpp, call setCategoryAmbient() method
- In each scene’s foreground delegate, if isOtherAudioPlaying() is true, manage BGM not to be played
GameUtil.h
class GameUtil { public: static bool setCategoryAmbient(); static bool isOtherAudioPlaying(); }
GameUtil.mm
#import <AVFoundation/AVFoundation.h> bool GameUtil::setCategoryAmbient() { NSError* error= nil; AVAudioSession* audioSession= [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryAmbient error:&error]; if (error) return false; else return true; } bool GameUtil::isOtherAudioPlaying() { AVAudioSession* audioSession= [AVAudioSession sharedInstance]; return [audioSession isOtherAudioPlaying]; }