Search code examples
objective-ccocoaxcodeitunesvolume

Objective-C Method to mute and unmute volume


I'm a little stuck, i'm trying to write a method which when a button is pressed; will get the current volume of iTunes, store the volume as an int declared as x. Then make the iTunes volume equal to 0, which will essentially mute the iTunes volume, but then i want the iTunes volume to return to the int x if the button is pressed again, which will essentially unmute the iTunes volume and restore it to the original volume.

Here's what i have so far:

- (IBAction)muteAndUnmute:(id)sender {
    iTunesApplication *iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
    int x;
    x = [iTunes soundVolume];
    if ([iTunes soundVolume] > 0 ) {
        [volumeSlider setIntValue:0];
        [iTunes setSoundVolume:[volumeSlider intValue]];
        [volumeLabel setIntValue:[volumeSlider intValue]];}
    }

Any help would be much appreciated, i think it's quite easy to do but just can't get my head around it, thanks in advance, Sami.


Solution

  • make your volume value (vol) as class variable and not local, then

    // MyWindowController.h
    @interface MyWindowController : NSWindowController {
        int  vol;
    }
    - (IBAction)btnPressed:(id)sender;
    @end
    
    
    // MyWindowController.m    
    @implementation MyWindowController
    
    - (id)init {
        if (self = [super init]) {
            vol = 0;
        }
       return self;
    }
    
    
    - (IBAction)btnPressed:(id)sender
    {
    
            id iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
            if ([iTunes soundVolume] > 0 )
            {
                vol = [iTunes soundVolume];
                [iTunes setSoundVolume:0];
            }
            else
                [iTunes setSoundVolume:vol];
    
    }
    
    @end