【发布时间】:2015-07-04 12:55:23
【问题描述】:
我知道有很多像我这样的问题,但没有任何效果 对我来说。
我试图让AVPlayer 在我退出应用程序时继续播放,我已经实现了以下Singleton Class:
.h 文件:
#import <AVFoundation/AVFoundation.h>
#import <Foundation/Foundation.h>
@interface LiveStreamSingleton : NSObject<AVAudioPlayerDelegate>{
}
+(LiveStreamSingleton *)sharedInstance;
-(void)playStream;
-(void)stopStream;
-(bool)status;
@end
.m 文件:
#import "LiveStreamSingleton.h"
static LiveStreamSingleton *sharedInstance = nil;
@interface LiveStreamSingleton (){
AVPlayer *audioPlayer;
}
@end
@implementation LiveStreamSingleton
+ (LiveStreamSingleton*) sharedInstance {
static dispatch_once_t _singletonPredicate;
static LiveStreamSingleton *_singleton = nil;
dispatch_once(&_singletonPredicate, ^{
_singleton = [[super allocWithZone:nil] init];
});
return _singleton;
}
+ (id) allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
-(void)playStream{
//NSError *error = nil;
NSURL *urlStream;
NSString *urlAddress = @"http://198.178.123.23:8662/stream/1/;listen.mp3";
urlStream = [[NSURL alloc] initWithString:urlAddress];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:urlStream options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
audioPlayer = [AVPlayer playerWithPlayerItem:playerItem];
//This enables background music playing
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer = [AVPlayer playerWithURL:urlStream];
if(!audioPlayer.error){
NSLog(@"Trying to play from singleton!");
[audioPlayer play];
NSLog(@"rate: %f",audioPlayer.rate);
}
}
-(void)stopStream{
NSLog(@"Trying to stop from singleton!");
[audioPlayer pause];
}
-(bool)status{
bool stat;
if(audioPlayer.rate > 0){
stat = true;
}else{
stat = false;
}
return stat;
}
@end
我已将[[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 设置为在后台播放,但我在我的真实 ipad 上尝试过,它不起作用。
有什么想法吗?
【问题讨论】:
标签: ios objective-c swift avplayer