Planky
Planky

Reputation: 35

How to make a Custom UIButton to toggle a Sound On/Off

i am an n00b and seeking help.

Now i can start a Soundfile with Following code:

- (void)addButtonSpeaker {
UIButton *buttonSpeaker = [UIButton buttonWithType:UIButtonTypeCustom]; 
                            [buttonSpeaker setFrame:CGRectMake(650, 930, 63, 66)];
[buttonSpeaker setBackgroundImage:[UIImage imageNamed:@"buttonLesen.png"] 
                         forState:UIControlStateNormal];
[buttonSpeaker addTarget:self action:@selector(playAudio)
        forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonSpeaker];
 }

- (void)playAudio {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Vorwort" ofType:@"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL    
 fileURLWithPath:path] error:NULL];
self.audioPlayer = theAudio;
[theAudio release];
[theAudio play];
 }

With the same Button i would like to stop and play the sound. Maybe i am searching for the wrong thing, but i can´t find the proper information on the web.

It would be really helpful if someone could give me a LINK to a tutorial or something like this.

thanks in advance Planky

Upvotes: 1

Views: 550

Answers (1)

EmptyStack
EmptyStack

Reputation: 51374

Create the AVAudioPlayer player object on loadView or somewhere.

- (void)loadView {

    // Some code here
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Vorwort" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    self.audioPlayer = theAudio;
    [theAudio release];
    // Some code here
}

Then inside the button's action(change the action name to toggleAudio as others suggested), you can get the property isPlaying to see whether audio is playing or not, and do the respective actions.

- (void)toggleAudio { // original name is playAudio

    if ([self.audioPlayer isPlaying]) {

        [self.audioPlayer pause]; 
        // Or, [self.audioPlayer stop];

    } else {

        [self.audioPlayer play];
    }
}

Upvotes: 1

Related Questions