0

因此,我有这个应用程序在哪里播放视频,当您退出应用程序时,我希望用户继续收听视频的音频。我使用MPMoviePlayerController来播放视频,它在应用程序中工作得很好。在播放视频之前,我还设置了AVAudioSession,并且没有发生错误。在后台播放MPMoviePlayerController音频流

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

我也设置在plist背景模式音频。但是,关闭应用程序后,视频和音频都停止播放。我也导入了AVFoundation框架。

+2

尝试,而不是''AVAudioSessionCategoryPlayback所以 – falcon143 2014-08-28 04:55:04

+0

我代替我的视频和音频流,与音频流仅此'AVAudioSessionCategorySoloAmbient'。它在后台运行。但不是我的视频和音频流。我可以喜欢从MPMoviePlayerController中提取音频流并分别播放吗? – Victor 2014-08-28 15:23:45

+0

在这里我发布了答案:[MPMoviePlayerController音频流在后台](http://stackoverflow.com/a/30984609/3657875) – davidrl1000 2015-06-22 16:04:25

回答

0

只需在.plsit文件中设置Application does not run in backgroundNO

+0

请确保您在使用此变体之前检查商店提交准则。 – Till 2014-08-28 12:28:46

+0

@NANNAV这对iOS 6+版本仍然需要吗?我认为它自iOS 4以来默认设置为NO。 – Victor 2014-08-28 15:12:43

0

你需要让夫妇的plist file.i.e.变化

1)设置所需的背景模式到App播放音频

2)设置在应用背景不运行为YES。

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

然后,你需要在AppDelegate中

写这些太多的代码现在,您可以轻松地运行,而手机屏幕锁音频或进入后台。

+1

如果你看看我提供的代码,我已经实现了代码。 – Victor 2014-08-28 15:14:06

0

这段代码适用于我,首先你必须让你的应用程序有权在后台继续播放音乐(在你的.plis中),然后转到希望的类并实现此代码,首先导入和播放音乐的方法。

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

---- ----Ø

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

该文件是m3u8或mp4,而不是mp3。从我读过的内容中,我需要以某种方式从视频和播放中提取音频流。 – Victor 2015-06-22 22:59:20

0

您需要打开的功能背景模式。

As shown in figure checkmark the modes you want in background

相关问题