MPMoviePlayerController playing audio stream in the background

后端 未结 2 1228
不思量自难忘°
不思量自难忘° 2021-01-03 03:55

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 =          


        
2条回答
  •  离开以前
    2021-01-03 04:50

    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 
    #import 
    #import 
    

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

提交回复
热议问题