开发者

AVAudioPlayer UIButton - second touch stop current audio play

I have a UIButton that when touched plays an audio file. At the moment touching the button twice in succession plays the audio file twice instead of stopping it.

I'm looking to have the second click stop the audio file and not play a second instance. any suggestions would be very much appreciated. thanks

-(IBAction) buttonNoisePlay {

        NSString *pathsoundFile = [[NSBundle mainBundle] pathForResource:@"noise" ofType:@"mp4"];
        sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathsoundFile] error:NULL];
        sound.delegate = self;
        sound.numberOfLoops = -1;
        sound.volume = 1;   

            if(sound == nil || sound.playing == NO)  //if not playi开发者_Go百科ng
            {

                    [sound play];
            }
            else
            {
                    [sound stop];
            }
}


hmm, this is what I do & it only plays once:

-(void) playSound: (NSString *) strFileName
{       
    if(audioPlayer == nil || audioPlayer.playing == NO)  //check if it's already playing in case they dbl-tapped (or more) b/c we only want to play it once per found item
    {
        //Get the filename of the sound file:
        NSString *urlAddress = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], strFileName];

        //Get a URL for the sound file
        NSURL *url = [NSURL fileURLWithPath:urlAddress];
        NSError *error;

        //Use AVAudioPlayer to play the sound
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        audioPlayer.numberOfLoops = 0;

        if (audioPlayer == nil)
            NSLog(@"audioPlayer nil Error:%@", [error description]);
        else
            [audioPlayer play];
    }
}

And in the header:

AVAudioPlayer *audioPlayer;

I should probably also be checking for nil before initializing the audioPlayer, so it's only done once... but for now - it works.


You could do something like this:

-(IBAction) buttonNoisePlay {

    if(sound == nil || sound.playing == NO)  //if not playing
    {
        ...
        //if nil initialize

        [sound play];
    }
    else
    {
        [sound stop];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜