我正在为 iOS 构建一个 MP3 播放器,可以播放网络上托管的音频文件。我想提供离线播放文件的功能,因此我可以使用 ASIHTTP 下载文件,但我似乎无法在应用程序文档目录中找到有关使用 mp3 初始化 AVPlayer 的信息。以前有人这样做过吗?还可能吗?
*我在下面发布了一个答案,展示了如何将 iOS AvPlayer 用于本地文件和 http 文件。希望这有帮助!
我决定回答我自己的问题,因为我觉得关于如何使用 Apple 提供的 AVPlayer 处理本地文件和流(通过 http)文件的文档很少。为了帮助理解该解决方案,我在 GitHub 上用 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 源代码 以获取该示例的工作示例。 希望这有帮助!
-更新 12/7/2015 我现在有一个AVPlayer
来使用本地 URL
file://
是的,可以下载 .mp3(或任何类型的文件)并将其保存到 NSDocument 目录中,然后您可以从中检索并使用 AVAudioPlayer 进行播放。NSURL * localURL = [NSURL URLWithString:[@"file://" stringByAppendingString:YOUR_LOCAL_URL]];
AVPlayer * player = [[AVPlayer alloc] initWithURL:localURL];
检索下载的音频并播放:
NSString *downloadURL=**your url to download .mp3 file**
NSURL *url = [NSURLURLWithString:downloadURL];
NSURLConnectionalloc *downloadFileConnection = [[[NSURLConnectionalloc] initWithRequest: [NSURLRequestrequestWithURL:url] delegate:self] autorelease];//initialize NSURLConnection
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileDocPath = [NSStringstringWithFormat:@"%@/",docDir];//document directory path
[fileDocPathretain];
NSFileManager *filemanager=[ NSFileManager defaultManager ];
NSError *error;
if([filemanager fileExistsAtPath:fileDocPath])
{
//just check existence of files in document directory
}
NSURLConnection is used to download the content.NSURLConnection Delegate methods are used to support downloading.
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSFileManager *filemanager=[NSFileManagerdefaultManager];
if(![filemanager fileExistsAtPath:filePath])
{
[[NSFileManagerdefaultManager] createFileAtPath:fileDocPath contents:nil attributes:nil];
}
NSFileHandle *handle = [NSFileHandlefileHandleForWritingAtPath:filePath];
[handle seekToEndOfFile];
[handle writeData:data];
[handle closeFile];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alertView=[[UIAlertViewalloc]initWithTitle:@”"message:
[NSStringstringWithFormat:@"Connection failed!\n Error - %@ ", [error localizedDescription]] delegate:nilcancelButtonTitle:@”Ok”otherButtonTitles:nil];
[alertView show];
[alertView release];
[downloadFileConnectioncancel];//cancel downloding
}
只需编写代码即可使用 AudioURL 播放音频
我想知道您在这方面是否有任何澄清。
谢谢你
试试这个
NSString *docDir1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *myfilepath = [docDir1 stringByAppendingPathComponent:YourAudioNameinNSDOCDir];
NSLog(@”url:%@”,myfilepath);
NSURL *AudioURL = [[[NSURLalloc]initFileURLWithPath:myfilepath]autorelease];
Swift 本地播放版本,假设我的包中有一个文件“shelter.mp3”:
@IBAction func button(_ sender: Any?) {
guard let url = Bundle.main.url(forResource: "shelter", withExtension: "mp3") else {
return
}
let player = AVPlayer(url: url)
player.play()
playerView?.player = player;
}
我观察到你需要有正确的文件扩展名,否则你会看到黑屏,播放器图标被划掉。 您需要为下载的文件添加文件扩展名,例如 .m4v 或 .mov。