0

I have a music button in the main UI of iOS and I want the button function as stop music button and at the same time can play the music again. My problem is I can only stop the music but can't play it again. Here is my iOS code in xcode4. How can I define one button for both play and stop music button? I have assigned one button for both stopMusic and playMusic but it doesn't work.

- (IBAction)stopMusic{  
    self.playBgMusic.enabled = YES;
    [self.player stop];

}

- (IBAction)playMusic{

    self.playBgMusic.enabled = YES;
    [self.player play];

}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
    self.player=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    player.delegate = self;
    [player play];
    player.numberOfLoops = -1;
    [super viewDidLoad];
}
Amink
  • 35
  • 11

1 Answers1

0

Rather than have a single button try to send two different messages (stopMusic, playMusic), have it send toggleMusic every time. The toggleMusic method can then stop or play the music based on the current state of the player.

   - (IBAction)toggleMusic{  
        if ([self.player isPlaying] == YES) {
         [self.player stop];
        } else {
         [self.player play];
        }
        self.playBgMusic.enabled = YES;

    }
Mike Fahy
  • 5,487
  • 4
  • 24
  • 28
  • Your code is working but when i toggle it, the program quit with program received signal. Here is the line code error int retVal = UIApplicationMain(argc, argv, nil, nil); How do i release from memory? Almost successfully. You should thank you a lot. – Amink Dec 07 '11 at 14:58
  • - (void)dealloc { [player release]; [super dealloc]; } I just added this release but doesn't work. The program quit accidentally. – Amink Dec 07 '11 at 15:04