【问题标题】:Play MPMoviePlayerController audio stream in background在后台播放 MPMoviePlayerController 音频流
【发布时间】:2014-08-28 04:40:52
【问题描述】:

所以我有这个应用程序,我可以在其中播放视频,当您退出应用程序时,我希望用户继续收听视频的音频。我使用 MPMoviePlayerController 播放视频,它在应用程序中运行良好。我还在播放视频之前设置了 AVAudioSession,我没有收到任何错误。

NSError *audioSessionError;
NSError *activationError;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError];
[audioSession setActive:YES error:&activationError];

我还设置了 plist 背景模式音频。但是,当您关闭应用程序时,带有音频的视频都会停止播放。我还导入了 AVFoundation 框架。

【问题讨论】:

  • 试试这个AVAudioSessionCategorySoloAmbient而不是AVAudioSessionCategoryPlayback
  • 所以我用纯音频流替换了我的视频和音频流。它在后台工作。但不是我的视频和音频流。我可以从 MPMoviePlayerController 中提取音频流并单独播放吗?

标签: ios objective-c xcode mpmovieplayercontroller avaudiosession


【解决方案1】:

只需在 .plsit 文件中将 Application does not run in background 设置为 NO

【讨论】:

  • 确保在使用此变体之前检查商店提交指南。
  • @NANNAV iOS 6+ 版本还需要这个吗?从 iOS 4 开始,我认为它默认设置为 NO。
【解决方案2】:

您需要在 plist 文件中进行一些更改。

1) 将必需的后台模式设置为应用播放音频

2) 设置应用程序不在后台运行为YES。

 NSError *setCategoryErr = nil;
 NSError *activationErr  = nil;
 [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback    error:&setCategoryErr];
 [[AVAudioSession sharedInstance] setActive:YES error:&activationErr];

那么,你需要在 AppDelegate 中写这么多代码

现在,您可以在手机屏幕锁定或进入后台时轻松播放音频。

【讨论】:

  • 如果您查看我提供的代码,我已经实现了该代码。
【解决方案3】:

此代码对我有用,首先您必须授予您的应用权限以继续在后台播放音乐(在您的 .plis 中),然后转到希望的类并实现此代码,首先是导入和方法播放音乐。

#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMediaItem.h>
#import <AVFoundation/AVFoundation.h>

---- o ----

-(void) playMusic{

     [[AVAudioSession sharedInstance] setDelegate: self];

     NSError *myErr;

     // Initialize the AVAudioSession here.
    if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&myErr]) {
       // Handle the error here.
       NSLog(@"Audio Session error %@, %@", myErr, [myErr userInfo]);
    }else{
       // Since there were no errors initializing the session, we'll allow       begin receiving remote control events
       [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    }

    //initialize our audio player
    audioPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:@"http://www.cocoanetics.com/files/Cocoanetics_031.mp3"]];

    [audioPlayer setShouldAutoplay:NO];
    [audioPlayer setControlStyle: MPMovieControlStyleEmbedded];
    audioPlayer.view.hidden = YES;

    [audioPlayer prepareToPlay];

    [audioPlayer play];
}//end playmusic

【讨论】:

  • 文件是 m3u8 或 mp4,而不是 mp3。根据我的阅读,我需要以某种方式从视频和播放中提取音频流。
【解决方案4】:

您需要在功能中打开后台模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多