简体   繁体   中英

Stop Playing Audio when come back to View Controller in iOS

I am playing audio from playlist in my app. I am using following code in viewDidLoad function:-

    NSURL *url = [NSURL URLWithString:FeedLink];
    NSData *_objectData = [NSData dataWithContentsOfURL:url];
    NSError *error;

    audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
    audioPlayer.delegate = self;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    audioPlayer.numberOfLoops =  0;

On Play button it play the audio and it also playing fine in background or when i go to another class.

The problem is when i came back to this view controller and select another audio then the previous Playing audio is not stopped. and both are Playing simultaneously.

Can any one help me in this that when i came back to viewDidLoad from anther view controller it stop the playing audio and only play one at a time. Thanks in advance

In viewwillappear of the class where you are playing the audio use below code.then playing stopped when you back to that class.

-(void)viewwillappear{
    [audioPlayer stop];
}

Before playing any Audio file add a check of wether any Audio file is playing on or not.

Add below code for that.

if(audioPlayer.isPlaying){
[audioPlayer stop];
}

Then after play your next audio file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM