Detecting ipod music playback

It seems that in the current version (1.6.0f1) of Unity iPhone it's possible to play a compressed audio stream whilst ipod is playing music. Although I haven't really analysed it, it looks like the Unity music stream is decoded in software when the ipod background music is playing (sounds logical as there's supposedly only one hardware decode path).

As I actually like to give the player the option to have his ipod music playing, is there a way from within Unity to detect if music is already playing or not, or must I write a plugin for that?

(Browsing through the script reference it seems there isn't a way to do this from within Unity, but maybe I'm missing something or maybe there's an undocumented feature :-))

For this purpose I wrote this plugin and added it to my appDelegate.m (renamed to .mm and compiled as a C++ file):

    extern "C" {

    bool _IsMusicPlaying () {
        BOOL isPlaying = NO;
        MPMusicPlayerController* iPodMusicPlayer = [MPMusicPlayerController iPodMusicPlayer];
        if (iPodMusicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
            isPlaying = YES;
        }
        NSLog(@"Music is %@.", isPlaying ? @"on" : @"off");
        return isPlaying;
    }   
}

Unity can then call this method through a plugin class and get the state of the iPod music. I hope that's useful.

EDIT (added unity code too): In the Assets/Plugin folder of your unity project, create a OBJCPlugin.cs file and add:

    using UnityEngine;
using System.Runtime.InteropServices;

public class OBJCPlugin 
{

    [DllImport ("__Internal")]
    private static extern bool _IsMusicPlaying ();

    public static bool IsMusicPlaying ()
    {
        if ( Application.platform == RuntimePlatform.IPhonePlayer )
        {
            return _IsMusicPlaying();
        }
        else {
            return false;
        }
    }
}

Then you can call that static method of that class from any other class.

I think a much simpler solution would be to provide the player with an option to mute your game.

There isn't anything like this in the Unity API, but you can probably get what you need with a plugin.

One solution might be to modify the Objective C shell that Unity creates and have it do the check for the iPod audio playback and write something to the player prefs.

Another way is that you could post an idea on feedback.unity3d.com and maybe it will get released in unity 3.1 or something