obj-c:在Document目录中播放mp3文件

时间:2014-12-27 09:49:13

标签: ios objective-c

我正在尝试从应用程序的文档目录中播放一首歌,这里有一些代码。 URL,Asset,PlayerItem和Player似乎都有有效值。这首歌仍然没有播放。有什么想法吗?

-(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];

}
}

我的项目中有这两个框架

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

1 个答案:

答案 0 :(得分:3)

当您尝试从本地路径播放歌曲时,您应该使用NSURL fileURLWithPath,也不要在播放器上添加状态通知观察器。请参阅以下示例源代码:

@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