0

I added a button to my storyboard, and assigned a music to be played when the button is clicked. I used the event touch up inside

My question is, how can I make the button to toggle the music on and off when it is clicked.

Thanks

==================================================================================

For those of you who are interested in seeing the App, I made a repository on github. Here's the link https://github.com/edwinlimantara/IncrediboxV2. Please contribute, if you feel it is an interesting project.

I tried to make something similar to http://incredibox.com/v2/. Check it out! It is a very cool website.

3 Answers 3

3

If you are using AVAudioPlayer you can toggle the music player on button tap like:

if(audioPlayer.isPlaying){
    [audioPlayer stop];
    audioPlayer = nil;
}else{
    // initialize audio player and play
}
1
  • Oh thank you so much, I didn't know .isPlaying before
    – dodgerblue
    Dec 30, 2013 at 5:54
1

You can do like below, say below method is called on button tap event then,

   -(IBAction)pushClicked:(id)sender
 {
      UIButton *mButton = (UIButton*)sender;
if (mButton.selected==NO)
{
    [mButton setSelected:YES];

    //do your stuff here;
}
else if (mButton.selected==YES)
{
    [mButton setSelected:NO];
    // do your stuff here
}


}
1
  • It's probably better to take advantage of using .isPlaying in AVAudioPlayer. Thanks anyway for your answer
    – dodgerblue
    Dec 30, 2013 at 6:05
1

Better you can use UISwitch rather than button to toggle. If you want to use UIButton then you can use tags and and two different images.

if(soundButton.tag == 1)
{
 if(audioPlayer.isPlaying){
    [audioPlayer stop];
    audioPlayer = nil;
    soundButton.tag = 0; 
// Change the button image to Off
 }
 else{
    // initialize audio player and play
 }
}
else
{
    soundButton.tag = 1; 
// Play the music & Change the button image to ON

}
1
  • That's a good idea. I can also change the image, that's even better. Thank you
    – dodgerblue
    Dec 30, 2013 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.