簡體   English   中英

iOS如何停止在后台播放音頻?

[英]iOS how to stop audio playing in background?

在我的應用中,我正在播放實時音頻流,音頻也會繼續在后台播放,為此我正在使用

// 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;

我可以在背景/前景中播放音頻。 流url連續發送音頻,我的應用程序在后台連續播放音頻,但是在特定時間我想停止音頻播放器。 所以我的問題是,如果我的應用程序在后台運行(在后台播放),如何停止音頻播放器?

您可以使用以下方法之一調用停止音頻代碼以在后台運行應用程序時停止音頻...在appdelegate類中,通過使用以下選項

  1. 您可以直接在音頻播放器實例方法上調用audioplayer stop方法,或者
  2. 您可以為此使用觀察者

  - (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

}

//注冊通知viewdidload中的音頻播放器在哪里

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

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

AVQueuePlayer繼承自AVPlayer 您可以使用暫停方法來暫停播放。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM