NSSound Class help

Discussion in 'Mac Programming' started by MacProgramer, Nov 26, 2008.

  1. MacProgramer macrumors newbie

    Joined:
    Nov 26, 2008
    #1
    ok i am currently teaching myself how to develop for Leopard
    (Cocoa + Objective-C)

    i need help with a program using the NSSound Class

    here is the code

    Code:
    #import "AppController.h"
    
    @implementation AppController
    - (IBAction)playMusic:(id)sender
    
    {
    	NSSound* sound = [[NSSound alloc] initWithContentsOfFile: @"/Users/HomePortal/Music/TI - Whatever You Like.mp3" byReference:YES];
    	[sound play];
    }
    
    - (IBAction)stopMusic:(id)sender
    {
    	
    }
    
    @end
    
    
    how do i get the action stopMusic: to stop the music when i press the button linked to the action stopMusic:

    , any help would be appreciated
     
  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    Instead of declaring sound inside the playMusic: method, declare it as an instance variable in your .h. Something like:

    Code:
    @interface AppController {
        [b][color=red]NSSound *sound;[/color][/b]
    }
    ...
    @end
    By declaring it here, the variable is accessible in any method in the class.

    So then your playMusic: method might look like this:

    Code:
    - (IBAction)playMusic:(id)sender
    {
        sound = [[NSSound alloc] initWithContentsOfFile: @"/Users/HomePortal/Music/TI - Whatever You Like.mp3" byReference:YES];
        [sound play];
    }
    And stopMusic:

    Code:
    - (IBAction)stopMusic:(id)sender
    {
        [sound stop];
    }
     

Share This Page