abdus.me
abdus.me

Reputation: 1819

making iOS app having option to enable and disable sound

i want to make iOS app with play sound on every button tap, and i can disable/Enable sound from setting screen. Can any one help me on this?

Upvotes: 4

Views: 2815

Answers (3)

Ajay Chaudhary
Ajay Chaudhary

Reputation: 1991

Ok, try this code

In your setting screen .h file

@interface SettingScreen : UIViewController<AVAudioPlayerDelegate,AVAudioSessionDelegate>
{
    AVAudioPlayer *audioplayer;
}

in .m file

-(void)viewDidLoad
{
    NSString* BS_path_blue=[[NSBundle mainBundle]pathForResource:@"Click" ofType:@"mp3"];
    audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue]  error:NULL];
    audioplayer.delegate=self;
    [audioplayer prepareToPlay];

    UISwitch *soundsOnOffButton = [[UISwitch alloc]initWithFrame:CGRectMake(180, 8, 130, 27)];
    [self.view addSubview:soundsOnOffButton];
    [soundsOnOffButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

     soundsOnOffButton.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"sound"];
}

-(void)buttonAction:(UIButton *)sender
{
    if (soundsOnOffButton.on)
    {

        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"sound"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"sound"]==YES)
        {
            [audioplayer play];
        }
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"sound"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

this is for setting screen. Now if you want to play a sound for any button in another screen , add delegate and frist four line to your that file then add this line to their action.

-(void)buttonAction:(UIButton *)sender
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"sound"]==YES)
    {
         [audioplayer play];
     }

    // other code
}

Revert me if any problem.

Upvotes: 2

calimarkus
calimarkus

Reputation: 9977

Just check the setting before playing any sound..?

// pseudo code
- (void)playSound:(NSInteger)soundID;
{
  if(settings.soundEnabled) {
    [SoundPlayer playSoundWithID:soundID];
  }
}

Upvotes: 1

Siba Prasad Hota
Siba Prasad Hota

Reputation: 4789

You cant change the Device sound(app will be rejected) how ever you can set volume By assigning some values between 0 to 1 .in your setting option if user selects disable then set it to 0. check sam's answer here : How to disable iOS System Sounds

Upvotes: 0

Related Questions