views:

33

answers:

2

I'd like to control an instance of AVAudioPlayer from a UITableView item in a didSelectRowAtIndexPath instance.

First touch of the row item triggers 'play' of the AVAudioPlayer. Second touch of the row item triggers 'stop' of the AVAudioPlayer.

I can make the 'play' work but can't get the 'stop' to work. Also, subsequent touches of the row item starts another thread of the audio in the background.

What's the best way to ensure 1 tap starts the audio and a 2nd tap stops it?

Code samples - this method preps audio file and AVAudioPlayer for use:

- (void)makeReadyAudio {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Murderers" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error;
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[musicPlayer prepareToPlay];
}

This block will start & stop the AVAudioPlayer within a case statement in the didSelectRowAtIndexPath section:

case 7: {
        //touch to start audio sound playing, touch again to  stop playing
        [self makeReadyAudio];
        if ([musicPlayer isPlaying]) {
            [musicPlayer stop];
            NSLog(@"musicPlayer tested to be playing, so stop it.");
        } else {
            [musicPlayer play];
            NSLog(@"musicPlayer tested to be *not* playing, so play it.");
        }
        break;
    }
+1  A: 

How about:

- (void) didSelectRowAtIndexPath:
{
    if (player.isPlaying) {
        [player stop];
    } else {
        [player start];
    }
}

In other words, keep the player around and see what it is doing.

St3fan
if ([player isPlaying]) { [player stop]; NSLog(@"player tested to be playing, so stop it.");} else { [player play]; NSLog(@"player tested to be *not* playing, so play it.");}Seemed plausible, no luck though. Same behavior, the 'true' test case never seems to be run. Repeated touches of the selected row print "player tested to be *not* playing, so play it" over and over again in the log...while playing the audio again.Hmm.
pteeter
Then show more code. Sounds like the error is somewhere else. LIke for example your AVAudioPlayer code.
St3fan
code added to above problem statement...sorry supported markup tags not most intuitive @ StackOverflow.
pteeter
A: 

The problem is that you call makeReadyAudio every single time the row is tapped. You need to check if you have already done that. For example by doing something like:

if (musicPlayer == nil) {
    [self makeReadyAudio];
}
St3fan
Of course. Ok next time I'm back at my development machine I'll give it a try.
pteeter