我正在为 iOS 构建一个 MP3 播放器,用于播放网络上托管的音频文件。我想提供离线播放文件的功能,因此我可以使用 ASIHTTP 下载文件,但我似乎无法在应用程序文档目录中找到有关使用 mp3 初始化 AVPlayer 的信息。以前有人这样做过吗?这可能吗?
*我在下面发布了一个答案,展示了如何将 iOS AvPlayer 用于本地文件和 http 文件。希望这有帮助!
最佳答案
我决定回答我自己的问题,因为我觉得关于如何使用 Apple 提供的 AVPlayer 处理本地文件和流(通过 http)文件的文档很少。为了帮助理解解决方案,我整理了一个 sample project on GitHub in Objective-C和 Swift下面的代码是 Objective-C,但你可以下载我的 Swift 示例来查看。非常相似!
我发现,除了如何实例化 Asset > PlayerItem > AVPlayer 链的 NSURL 之外,设置文件的两种方法几乎相同。
这是核心方法的概述
.h文件(部分代码)
-(IBAction) BtnGoClick:(id)sender;
-(IBAction) BtnGoLocalClick:(id)sender;
-(IBAction) BtnPlay:(id)sender;
-(IBAction) BtnPause:(id)sender;
-(void) setupAVPlayerForURL: (NSURL*) url;
.m文件(部分代码)
-(IBAction) BtnGoClick:(id)sender {
NSURL *url = [[NSURL alloc] initWithString:@""];
[self setupAVPlayerForURL:url];
}
-(IBAction) BtnGoLocalClick:(id)sender {
// - - - Pull media from documents folder
//NSString* saveFileName = @"MyAudio.mp3";
//NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString *path = [documentsDirectory stringByAppendingPathComponent:saveFileName];
// - - -
// - - - Pull media from resources folder
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyAudio" ofType:@"mp3"];
// - - -
NSURL *url = [[NSURL alloc] initFileURLWithPath: path];
[self setupAVPlayerForURL:url];
}
-(void) setupAVPlayerForURL: (NSURL*) url {
AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
player = [AVPlayer playerWithPlayerItem:anItem];
[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 Failed");
} else if (player.status == AVPlayerStatusReadyToPlay) {
NSLog(@"AVPlayer Ready to Play");
} else if (player.status == AVPlayerItemStatusUnknown) {
NSLog(@"AVPlayer Unknown");
}
}
}
-(IBAction) BtnPlay:(id)sender {
[player play];
}
-(IBAction) BtnPause:(id)sender {
[player pause];
}
查看 Objective-C source code举个例子。 希望这有帮助!
关于iphone - AVPlayer和本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9577471/