首页 文章

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

提问于
浏览
0

在我的应用程序中,我正在播放实时音频流,音频也继续在后台播放,因为我正在使用

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

我能够在后台/前台播放音频 . 流媒体网址连续发送音频,我的应用程序在后台连续播放音频,但在某个时间我想停止音频播放器 . 所以我的问题是如果我的应用程序在后台运行(在后台播放)如何停止音频播放器?

2 回答

  • 1

    您可以使用以下方法之一调用停止音频代码,以便在appdelegate类中使用以下选项在后台应用时停止音频

    • 您可以直接在音频播放器实例方法上调用audioplayer stop方法

    • 您可以使用观察者

    - (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中你的audioplayer在哪里

    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(stopAudioPlayer:) name: @"stopGCReaderAudioPlayer" object: nil];
    
    -(void)stopAudioPlayer: (NSNotification*)notification{
    [self.audioPlayer stop];
    self.audioPlayer = nil;
    }
    
  • 0

    AVQueuePlayer 继承自 AVPlayer . 您可以使用暂停播放的pause方法 .

相关问题