繁体   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