简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM