2012-08-13 146 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>

    相关问题