MPMoviePlayerController在后台播放音频流

时间:2012-02-25 16:05:20

标签: ios mpmovieplayercontroller

当应用程序进入后台时播放音频流时遇到了麻烦。

我使用代码启动流:

NSURL *mediaURL = [NSURL URLWithString:@"http://url.to.my.stream"];

MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] initWithContentURL:mediaURL];

[[NSNotificationCenter defaultCenter] addObserver:self 

                                         selector:@selector(moviePlayBackDidFinish:) 

                                             name:MPMoviePlayerPlaybackDidFinishNotification 

                                           object:nil]; 



[mp setControlStyle:MPMovieControlStyleFullscreen];

[mp setMovieSourceType:MPMovieSourceTypeStreaming];

[mp setFullscreen:YES];



[self.view addSubview:[mp view]];



[mp prepareToPlay];

[mp play];

它完美无缺。但是,当应用程序进入后台时,我在属性列表中设置了“App播放音频”标记,然后流停止播放。

如何让我的应用程序在后台播放音频流?

致以最诚挚的问候,非常感谢您的帮助!

2 个答案:

答案 0 :(得分:9)

我自己没有尝试过,但看起来很有希望:iOS Multitasking: Background Audio

  

创建项目后,转到APP-Info.plist并添加   UIBackgroundModes作为新行。然后它应该创建数组。

     

打开数组,在项目0的右侧将其设置为音频。

修改

您的AVAudioSession是否设置正确?

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];

答案 1 :(得分:0)

这段代码对我有用,首先你必须给你的应用程序权限,以便继续在后台播放音乐(在你的.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