如何保持声音关闭

时间:2014-07-16 16:40:26

标签: ios audio

我有两个按钮。一个显示声音正在播放时,另一个显示声音未播放时。但是,当我关闭它并切换视图控制器时。然后我回到主菜单视图控制器,声音重新开启。我想根据用户设置打开或关闭声音。

     (IBAction)pauseSound
{
    BOOL shouldPlaySound = YES;
    [[NSUserDefaults standardUserDefaults] setBool:shouldPlaySound forKey:@"shouldPlaySound"];
    if (![sound isPlaying]) {
        [sound play];
        [soundButton setBackgroundImage:[UIImage imageNamed:@"SoundOn.png"] forState:UIControlStateNormal];
    }else {
        [sound pause];
        [soundButton setBackgroundImage:[UIImage imageNamed:@"SoundOff.png"] forState:UIControlStateNormal];
         }
    [[NSUserDefaults standardUserDefaults] synchronize];
}

1 个答案:

答案 0 :(得分:0)

这样做的一个好方法是保存或不播放NSUserDefaults中的声音,因此您的应用会记住该设置。设置它,即通过

BOOL shouldMuteSound = ...//set it corresponding to your button presses/visibility
[[NSUserDefaults standardUserDefaults] setBool:shouldMuteSound forKey:@"shouldMuteSound"];
//call this to immediatly update the userDefaults
[[NSUserDefaults standardUserDefaults] synchronize];

并通过

加载
BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:@"shouldMuteSound"];

我一开始并没有得到它,按钮位于播放声音的同一个viewController中。该代码可以帮助您:

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:@"shouldMuteSound"];
    if(!shouldMuteSound){
        [self playSound];
    }else{
        [self stopSound];
    }
} 

- (void)playSound{
     if(!sound){
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Main Menu" ofType:@"mp3"];
        sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        sound.numberOfLoops = -1;
     }
    if (![sound isPlaying]){
        [sound play];
    }
    [soundButton setBackgroundImage:[UIImage imageNamed:@"SoundOn.png"] forState:UIControlStateNormal];
}

- (void)stopSound{
    [sound pause];
    [soundButton setBackgroundImage:[UIImage imageNamed:@"SoundOff.png"] forState:UIControlStateNormal];
}

- (IBAction)soundButtonTapped{
   BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:@"shouldMuteSound"];
   shouldMuteSound = !shouldMuteSound;
   [[NSUserDefaults standardUserDefaults] setBool:shouldMuteSound forKey:@"shouldMuteSound"];
   [[NSUserDefaults standardUserDefaults] synchronize];
   if(shouldMuteSound){
      [self stopSound];
   }else{
      [self playSound];
   }
}