iphone – AVAudioSession not working as described by Apple – Education Career Blog

My game has 3 background songs. I would like the game to set the background music to off when there is ipod music playing, else it will play the last played piece of music. When the muser changes the music with the ipod music on, the ipod music should go away and the background music plays. The problem is, the second time I try to do this (Changing the music from ipod to in-game) the first song will play but the other two will not.

This is stupid behaviour and it wont work any way I try to solve the problem. Here’s my current code….

In the drawRect loop:

//Music toggle
                        if(music_active == 0){
                            AVAudioSession sharedInstance setCategory:AVAudioSessionCategorySoloAmbient error:NULL;
                            AVAudioSession sharedInstance setActive:YES error:NULL;
                            background_music play;
                            music_active++;
                        }else if(music_active == 1){
                            background_music pause;
                            background_musicB play;
                            music_active++;
                        }else if(music_active == 2){
                            background_musicB pause;
                            background_musicC play;
                            music_active++;
                        }else{
                            background_musicC pause;
                            music_active = 0;
                        }

In the startAnimation method:

UInt32 size,result;
        size = sizeof(result);
        AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying,&size,&result);
        if(!result){
            AVAudioSession sharedInstance setCategory:AVAudioSessionCategorySoloAmbient error:NULL;
            AVAudioSession sharedInstance  setActive:YES error:NULL;
            background_music prepareToPlay;
            background_musicB prepareToPlay;
            background_musicC prepareToPlay;
            if(music_active == 1){
                background_music play;
            }else if(music_active == 2){
                background_musicB play;
            }else if(music_active == 3){
                background_musicC play;
            }
        }else{
            music_active = 0;
        }

In the stopAnimation method:

background_music stop;
        background_musicB stop;
        background_musicC stop;
        AVAudioSession sharedInstance setCategory:AVAudioSessionCategoryAmbient error:NULL;
         AVAudioSession sharedInstance setActive:NO error:NULL;

In the initWithCoder method:

AVAudioSession sharedInstance setCategory:AVAudioSessionCategorySoloAmbient error:NULL;

This method also loads the sound files and sets the number of loops to -1. It uses AVAudioPlayer, of-course.

Thank you for any help.

Leave a Comment