MPMoviePlayerController playing audio stream in th

2019-02-10 07:53发布

问题:

I am running into trouble with playing an audio stream when the application enters background.

I use the code to start the stream:

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

It works perfect. But allthough I set the flag 'App plays audio' in the property list when the app enters background the stream stops playing.

How do I make my application play the audio stream in the background?

Best regards and thanks a lot for help!

回答1:

I didn't tried it myself but this looks promising: iOS Multitasking: Background Audio

Once the project has been created go to APP-Info.plist and add UIBackgroundModes as a new row. It should then create the array.

Open the array and to the right of Item 0 set it to audio.

EDIT

Is your AVAudioSession set up properly?

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


回答2:

This code worked for me, first you must to give your app permissions to keep playing music in the background (In your .plis), after that go to the wished class and implement this code, first the imports and the the method to play the music.

#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