我正在开发一个音乐播放器应用并使用AVPlayer,我必须从文档目录播放音频并直接流式传输。但是我的AVPlayer消耗了大量的CPU,使应用程序停留在随机位置。
App Flow
我能得到任何帮助。
任何请让我知道音乐应用的CPU消耗是正常的。
由于
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentsDirectory = [pathArray objectAtIndex:0];
NSString* filePath = [documentsDirectory returnDocumentDirectoryPath:@"filename.mp3"];
NSURL *soundURL;
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
soundURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
}
if (_player != nil){
[_player pause];
[_player removeObserver:self forKeyPath:@"status"];
}
AVAsset *asset = [AVURLAsset URLAssetWithURL:soundURL options:nil];
AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
_player = [AVPlayer playerWithPlayerItem:anItem];
[_player addObserver:self forKeyPath:@"status" options:0 context:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:[_player currentItem]];
使用以下代码更改音轨时
[_player replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithAsset:[AVURLAsset URLAssetWithURL:soundURL options:nil]]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:[_player currentItem]];
[_player play];
在线直播
if(!_player)
_player = [[AVPlayer alloc] init];
resourcePath=@"www.google.com/abc.mp3"//stream URL
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:resourcePath] options:nil];
NSArray *keys = [NSArray arrayWithObject:@"playable"];
[asset loadValuesAsynchronouslyForKeys:keys completionHandler:^() {
if(!playerPlaying){
[_player replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithAsset:asset]];
}
}];