I'm trying to play a song from app's document directory, here is some code. The URL, Asset, PlayerItem and Player all seem to have valid values. Still the song doesn't play. Any thoughts why?
-(void) playFileAtLocalURL: (NSString*) urlAsString{
if([[NSFileManager defaultManager] fileExistsAtPath:urlAsString])
{
self.asset = [AVAsset assetWithURL:[NSURL URLWithString:urlAsString ]];
self.playerItem = [[AVPlayerItem alloc] initWithAsset:self.asset];
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
[self.player play];
}
}
I have these two frameworks in my project
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
As you are trying to play song from local path then you should use NSURL fileURLWithPath , also you are not adding status notification observer on player . Refer below sample source code:
@interface ViewController : UIViewController{
AVPlayer *_player;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *mp3Path = [[NSBundle mainBundle] pathForResource:@"kk" ofType:@"mp3"];//Your Document mp3 path
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:mp3Path
] options:nil];
AVPlayerItem *_playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
_player = [[AVPlayer alloc]initWithPlayerItem:_playerItem];
[_player addObserver:self forKeyPath:@"status" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if (object == _player && [keyPath isEqualToString:@"status"])
{
if (_player.status == AVPlayerStatusFailed)
NSLog(@"AVPlayer Status Failed");
else if (_player.status == AVPlayerStatusReadyToPlay)
{
//Start playing song
[_player play];
}
else if (_player.status == AVPlayerItemStatusUnknown)
NSLog(@"AVPlayer Status Unknown");
}
}
@end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.