2012-08-24 225 views
1

我在表格视图中显示媒体层次结构时,当我点击表格视图中的歌曲时,它使用MPMoviePlayerViewController播放歌曲。但是当我点击完成按钮时,声音停止播放。我做了以下代码:在后台播放音频

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

我想要浏览媒体层次结构以及在后台播放歌曲。如何做呢?

回答

4

您应该启动AVAudioSession并在主plist中声明您的应用程序在后台播放音乐。

在didFinishLaunchingWithOptions:

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

在applicationDidBecomeActive:

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

在主plist中加入:所需的背景模式 - 应用程序播放音频

+0

didFinishLaunchingWithOptions:? –

+0

@VXtreme它在你的AppDelegate.m文件中。此外,如果您正在播放音频,为什么您要使用电影播放器​​? –

+0

我的意思是应用程序:didFinishLaunchingWithOptions::) – selfsx

2

这听起来像你没有正确设置你的音频会话。从

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

例如,使用默认的音频会话时,在应用程序中的音频停止时自动锁定期间超时和屏幕锁。如果你想确保继续播放与屏幕锁定,包括在应用程序的初始化代码下面几行:

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

的AVAudioSessionCategoryPlayback类别可确保继续播放,屏幕锁定时。激活音频会话将使指定的类别生效。

+0

是的,我也没有设置音频会议,但我困惑在哪里设置它? –