Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play music in the background using AVAudioplayer

I want to play music even if the app goes in background. I checked all stackoverflow links but none of them worked. Please help need to do it today.

I had used following code:-

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Day At The Beach"  ofType: @"mp3"];  NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];  NSError *error; playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error]; playerTemp.numberOfLoops = 0; AudioSessionSetActive(true); [playerTemp play]; 
like image 267
leena Avatar asked Oct 01 '11 11:10

leena


People also ask

How to allow music to play in background iPhone?

Go to Settings > Accessibility > Audio/Visual > Background Sounds, then turn on Background Sounds. Set any of the following: Sound: Choose a sound; the audio file downloads to your iPhone.

Does apple music have background play?

Turn on Background SoundsTap Background Sounds to turn it on. Tap the name of the current sound to view other sounds, then tap a sound name to listen to a preview. After you choose a sound, tap outside of the card to go back.


1 Answers

I had solved this question by referring iOS Application Background tasks

and make some changes in .plist file of our application..

Update

write this code in your controller's view did load method like this

- (void)viewDidLoad {     NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" ofType:@"mp3"]];     AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];     [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];     [[AVAudioSession sharedInstance] setActive: YES error: nil];     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];     [audioPlayer play];     [super viewDidLoad]; } 
like image 69
Mehul Mistri Avatar answered Oct 09 '22 09:10

Mehul Mistri