Bharat
Bharat

Reputation: 3007

iOS how to stop audio playing in background?

In my app i'm playing live audio stream, audio also continue playing in background, for this i'm using

// Set AVAudioSession
    NSError *sessionError = nil;
    // [[AVAudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];

    // Change the default output audio route
    UInt32 doChangeDefaultRoute = 1;
 AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
    self.player = [[AVQueuePlayer alloc] initWithURL:[NSURL URLWithString:streamingUrl]];
    self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

I'm able to play audio in background/foreground. The streaming url sends audio continuously and my app play audio continuously in background, but at a certain time i want to stop audio player. So my question is how to stop audio player if my app is running in background (playing in background)?

Upvotes: 1

Views: 2372

Answers (2)

abrar ul haq
abrar ul haq

Reputation: 404

you can call stop audio code in one of the following methods to stop your audio when application in background... in appdelegate class by using following options

  1. You can directly call audioplayer stop method on audio player instance method Or
  2. You can use observer for this

  - (void)applicationWillResignActive:(UIApplication *)application

 {
[[NSNotificationCenter defaultCenter] postNotificationName: @"stopGCReaderAudioPlayer" object: Nil];
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

  }

- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
// to stop media player

}

// Register Notification where is your audioplayer in viewdidload

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(stopAudioPlayer:) name: @"stopGCReaderAudioPlayer" object: nil];

-(void)stopAudioPlayer: (NSNotification*)notification{
[self.audioPlayer stop];
self.audioPlayer = nil;
}

Upvotes: 1

sgl0v
sgl0v

Reputation: 1417

The AVQueuePlayer is inherited from AVPlayer. You can use pause method that pauses playback.

Upvotes: 0

Related Questions