您可以将此作为后台音频任务执行,这样即使在用户按下主页按钮并且您的应用进入后台后,音频仍会继续播放。首先你创建一个 AVAudioSession。然后在 viewDidLoad 方法中设置一个 AVPlayerObjects 和一个 AVQueuePlayer 数组。 Ray Wenderlich 有一个很棒的教程,详细讨论了所有这些内容http://www.raywenderlich.com/29948/backgrounding-for-ios。您可以设置一个回调方法(观察者方法),以便应用在 - (void)observeValueForKeyPath 中流式传输时向其发送额外的音频数据。
代码如下所示(来自 Ray Wenderlich 的教程):
在 viewDidLoad 中:
// Set AVAudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
// Change the default output audio route
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
NSArray *queue = @[
[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"IronBacon" withExtension:@"mp3"]],
[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"FeelinGood" withExtension:@"mp3"]],
[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"WhatYouWant" withExtension:@"mp3"]]];
self.player = [[AVQueuePlayer alloc] initWithItems:queue];
self.player.actionAtItemEnd = AVPlayerActionAtItemEndAdvance;
[self.player addObserver:self
forKeyPath:@"currentItem"
options:NSKeyValueObservingOptionNew
context:nil];
在回调方法中:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"currentItem"])
{
AVPlayerItem *item = ((AVPlayer *)object).currentItem;
self.lblMusicName.text = ((AVURLAsset*)item.asset).URL.pathComponents.lastObject;
NSLog(@"New music name: %@", self.lblMusicName.text);
}
}
不要忘记在实现文件中添加视图控制器私有 API 中的成员变量:
@interface TBFirstViewController ()
@property (nonatomic, strong) AVQueuePlayer *player;
@property (nonatomic, strong) id timeObserver;
@end