1

我认为一切都在标题中。

我有一个播放音乐的 UIWebiew,当用户使用电源或主页按钮时,将应用程序置于后台,我希望音乐继续播放。

可能吗 ?

谢谢您的帮助 !

4

4 回答 4

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];
于 2012-08-15T01:39:23.740 回答
3

有点棘手,但这是可能的。来自下面的官方 Apple 文档:

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

您需要首先在您的 plist 中声明UIBackgroundModesfor audio,然后在您的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 播放音频时,您可以转到主屏幕,切换到另一个应用程序,或锁定屏幕,音频将继续播放。

于 2014-06-24T03:59:20.257 回答
1

我不相信这是可能的,即使在查看UIWebView了 的文档后,我也只发现了以下三个与媒体播放相关的属性。

  allowsInlineMediaPlayback  property
  mediaPlaybackRequiresUserAction  property
  mediaPlaybackAllowsAirPlay  property

不幸的是,他们都没有这样做。

于 2012-08-13T16:20:57.820 回答
0

对的,这是可能的。你需要做:

  1. 激活播放会话:

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

  1. 在 Info.plist 中添加音频背景模式:

所需的背景模式:应用程序使用 AirPlay 播放音频或流式传输音频/视频

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

于 2015-09-15T07:13:57.660 回答