Objective C: 切换视图后关闭音乐

Objective C: Turning off music after switching views

所以如果我留在同一个视图控制器上,我的音频工作正常,音乐会按照我想要的方式打开和关闭。但是,当我模态到另一个具有不同头文件的视图控制器并且 return 到我原来的视图控制器时,我无法再打开或关闭我的音乐。这是我的代码:

-(void) viewDidLoad {
//Play Background Music in .1 second after game loads
    [self performSelector:@selector(playBackgroundMusic) withObject:nil afterDelay:0.1];
}

-(void) playBackgroundMusic {

        //Music int is used so music doesnt play over itself
        if (musicInt == 0) {

            NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
            resourcePath = [resourcePath stringByAppendingString:@"/JungleMusic.wav"];
            NSLog(@"Path to play: %@", resourcePath);
            NSError* err;

            //Initialize our player pointing to the path to our resource
            player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                      [NSURL fileURLWithPath:resourcePath] error:&err];

            musicInt = musicInt + 1;
            //set our delegate and begin playback
            player.delegate = self;
            [player play];
            player.numberOfLoops = -1;
            player.currentTime = 0;
            player.volume = 1.0;
        }
}

//Used to turn the music on or off
    -(IBAction)musicTest:(id)sender{
        if (player.playing) {
            [player stop];
        } else {
            [player play];
        }
    }

我也在同一个.m文件中合成了我的播放器:

@synthesize player;

并且在我的 .h 文件中声明了 AVAudioPlayer

    @interface ViewController1 : UIViewController <AVAudioPlayerDelegate>

    {
        AVAudioPlayer *player;
    }

@property (nonatomic, retain) AVAudioPlayer *player;

如果能帮助解决这个问题,我们将不胜感激。我只是不明白为什么我不能在简单地建模到另一个视图控制器之后将我的音频 on/off 转换?谢谢!

根据我们在评论中的对话,答案是你有一个 segue 去第二个视图控制器,第二个 segue 返回,这实际上创建了原始视图控制器的一个新实例(你最后得到 三个 个视图控制器。)

解决方案是将后退按钮连接到调用 dismissViewController:animated:completion: 的 IBAction,或者将后退按钮连接到展开转场。当您执行其中一项操作时,后退按钮会关闭第二个视图控制器并公开现有的第一个视图控制器,而不是创建第二个视图控制器的新副本。