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.

  1. Write a bridge class between Objective-C and C++: e.g. GameUtil.h, GameUtil.mm
  2. Create following methods in GameUtil class
    1. setCategoryAmbient method to set Ambient category
    2. isOtherAudioPlaying method to get otherAudioPlaying property
  3. in the method of didFinishLaunching in AppDelegate.cpp, call setCategoryAmbient() method
  4. 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];
}