AVAudioSession does not work as described by Apple

There are 3 background songs in my game. I would like the background music to be turned off in the game when there is music for the iPod, otherwise it will play the last piece of music played. When music changes music from music to iPod, iPod music should go and background music will play. The problem is that the second time I try to do this (changing music from ipod to game), the first song will play, but the other two will not.

This is stupid behavior and it will not work as I try to solve the problem. Here is 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 downloads audio files and sets the number of cycles to -1. It uses AVAudioPlayer, of course.

.

+3

Source: https://habr.com/ru/post/1770626/


All Articles