2012-08-13 151 views

回答

5

你實際上不能用UIWebView做這件事,但你仍然可以做到這一點。該方法仍然通過URL將音頻從線上資源中分離出來。這裏有一些代碼可以幫助你。現在,假設您想在應用程序退出視頻時流式傳輸音頻,那麼它非常相似,但使用MediaPlayer框架而不是AVAudioPlayer框架。

NSURL *url = [NSURL URLWithString:@"http://website.com/audio.mp3"]; 

NSData *data = [NSData dataWithContentsOfURL:url]; 

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil]; 

[audioPlayer play]; 
+0

此其他帖子可能會幫助您使AVAudioPlayer在後臺播放音樂:http://stackoverflow.com/questions/3185621/is-it-possible-to-test-ios4-multitasking-background-music在這個模擬/ 3243857#3243857 – 2012-08-15 01:41:31

+0

謝謝克里斯,但我不認爲它會起作用,因爲我沒有在UIWebView中打開一個.mp3,實際上,我在soundcloud上播放音樂。用戶訪問配音列表並可以啓動一個。 – 2012-08-15 14:14:37

+0

可能有一個音頻文件鏈接到soundcloud的html5音頻播放器。檢查網站的來源,並查看它連接到的位置,以便將其音頻文件提供給html5音頻播放器 – 2012-08-16 23:07:25

0

我不相信這是可能的,甚至在檢查UIWebView的文檔後,我只發現以下三個與媒體播放相關的屬性。

allowsInlineMediaPlayback property 
    mediaPlaybackRequiresUserAction property 
    mediaPlaybackAllowsAirPlay property 

不幸的是,他們都沒有做到這一點。

3

有點棘手,但它是可能的。從下面的蘋果官方文檔:

https://developer.apple.com/library/ios/qa/qa1668/_index.html

您需要在您的plist首先聲明UIBackgroundModesaudio,然後寫了下面的代碼片段在AppDelegate

#import <AVFoundation/AVFoundation.h> 
#import <AudioToolbox/AudioToolbox.h> 

AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 

NSError *setCategoryError = nil; 
BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError]; 
if (!success) { /* handle the error condition */ } 

NSError *activationError = nil; 
success = [audioSession setActive:YES error:&activationError]; 
if (!success) { /* handle the error condition */ } 

現在,當你有音頻從UIWebView播放,您可以進入主屏幕,切換到另一個應用程序,或鎖定屏幕,音頻將繼續播放。

0

是的,這是可能的。你需要做的:

  1. 激活播放會話:

@import AVFoundation; [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];

  • 在你的Info.plist添加背景音頻模式:
  • 所需的背景模式:應用程序使用AirPlay播放音頻或流音頻/視頻

    <key>UIBackgroundModes</key> <array> <string>audio</string> </array>

    相關問題