Search code examples
iosavaudioplayeruiswitchmute

Mute AVAudioPlayer Background music with UISwitch


I am very new to programming and I am just working on my first app. I haven't been able to find an answer to this for weeks. I would really appreciate some help.

I have background music through AVAudioPlayer (the only sound in my app) that begins playing when my app opens - here is the code in my appdelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSString *bgmusic=[[NSBundle mainBundle]pathForResource:@"cloud_two-full-" ofType:@"mp3"];
    bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
    bgmusic1.delegate=self;
    bgmusic1.numberOfLoops=-1;

    [bgmusic1 play];
    [bgmusic1 setVolume:1.0];
}

So, I've created a uiswitch that I want to use to be able to mute the background music. Here is the IBAction in my viewcontroller.m:

- (IBAction)speakerOnOff:(id)sender {
    static BOOL muted = NO;

    if (muted) {
        [bgmusic1 setVolume:1.0];
    } else {
        [bgmusic1 setVolume:0.0];
    }
    muted = !muted;
}

But when I click the switch to off the music continues to play at its normal volume. I only have 1 view controller. Please help! I just want the music to mute when the switch is clicked to off and then back to volume 1.0 when the switch is back on.


Solution

  • Write this code

    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
    

    above

    bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
    

    and make your button action like this

    - (IBAction)speakerOnOff:(id)sender {
        if ( bgmusic1.volume == 0) {
            bgmusic1.volume = 1;
        } else {
            bgmusic1.volume =0;
        }
    }