V-Xtreme
V-Xtreme

Reputation: 7333

Playing audio in background

I am showing media hierarchy in the table view. When I tap on a song in the table view, it plays the song using MPMoviePlayerViewController. But when I click on the done button, the sound stops playing . I have created the following code:

        NSURL *songUrl=[operationControl getSong:stringId];
    mediaPlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:songUrl];
    [self presentModalViewController:mediaPlayerController animated:YES];
    [[mediaPlayerController moviePlayer] play];


I to want to browse the media hierarchy as well as play the song in the background. How can I achieve this?

Upvotes: 1

Views: 2171

Answers (2)

selfsx
selfsx

Reputation: 591

You should start AVAudioSession and declare in main plist that your application plays music in background.

in didFinishLaunchingWithOptions:

  // Setup audio session
  AVAudioSession *sharedSession = [AVAudioSession sharedInstance];
  [sharedSession setCategory:AVAudioSessionCategoryPlayback error:nil];

in applicationDidBecomeActive:

  [sharedSession setActive:YES error:nil]; // FIXME: Error handling

In main plist add: Required background modes - App plays audio

Upvotes: 4

Vishal
Vishal

Reputation: 556

It sounds like you didn't set up your Audio Session correctly. From

http://developer.apple.com/iphone/library/documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/UsingAudio.html

For example, when using the default audio session, audio in your application stops when the Auto-Lock period times out and the screen locks. If you want to ensure that playback continues with the screen locked, include the following lines in your application’s initialization code:

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

The AVAudioSessionCategoryPlayback category ensures that playback continues when the screen locks. Activating the audio session puts the specified category into effect.

Upvotes: 2

Related Questions