Play/Pause with the same button [AVAudioPlayer]

女生的网名这么多〃 提交于 2019-11-30 09:24:13
Splendid

Here's is simple method using BOOL Variable.

Set playing = NO in viewDidLoad.

-(void)PlayStop{    
    if (playing==NO) {
        // Init audio with playback capability
        [play setBackgroundImage:[UIImage imageNamed:@"hmpause.png"] forState:UIControlStateNormal];

        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:______ error:&err];
        [audioPlayer prepareToPlay];

        audioPlayer.delegate=self;
        [audioPlayer play];

        playing=YES;
    }
    else if(playing==YES){
        [play setBackgroundImage:[UIImage imageNamed:@"Audioplay.png"] forState:UIControlStateNormal];

        [audioPlayer pause];

        playing=NO;
    }
}

Keep your audioPlayer instance ready to play using the below method.

/*
 Prepares the audio file to play.
 */
-(void) initWithAudioPath:(NSString *) audioPath {
    // Converts the sound's file path to an NSURL object
    NSURL *audioPathURL = [[NSURL alloc] initFileURLWithPath:audioPath];

    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioPathURL error:nil];
    audioPlayer.delegate = self;

    [audioPlayer prepareToPlay];

    [audioPathURL release];
}

-(void) pausePlaybackForPlayer:(AVAudioPlayer *) player {
    [player pause];
}

-(void) startPlaybackForPlayer:(AVAudioPlayer *) player {
    if (![player play]) {
        NSLog(@"Could not play %@\n", player.url);
    }
}

- (IBAction)Beat {
    if (audioPlayer.playing == NO) {
        // Audio player is not playing.
        // Set the button title here to "stop"...
        [self startPlaybackForPlayer:audioPlayer];
    }else {
        // Audio player is playing.
        // Set the button title here to "play"...
        [self pausePlaybackForPlayer:audioPlayer];
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!