2012-08-24 42 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

是的,我也沒有設置音頻會議,但我困惑在哪裏設置它? –