AVPlayer和本地文件

时间:2012-03-06 03:20:12

标签: iphone ipad avfoundation avplayer

我正在为iOS制作MP3播放器,播放网络上的音频文件。我想提供离线播放文件的能力,所以我使用ASIHTTP下载文件,但我似乎无法在app文档目录中找到有关初始化AVPlayer的信息。有没有人这样做过?它甚至可能吗?

*我在下面发布了一个答案,其中显示了如何将iOS AvPlayer用于本地和http文件。希望这有帮助!

6 个答案:

答案 0 :(得分:34)

我决定回答我自己的问题,因为我觉得关于如何将Apple提供的AVPlayer用于本地和流(通过http)文件的文档很少。为了帮助理解解决方案,我将sample project on GitHub in Objective-CSwift放在一起。下面的代码是Objective-C,但您可以下载我的Swift示例来查看。它非常相似!

我发现设置文件的两种方式几乎相同,除了你如何为资产实例化NSURL> PlayerItem> AVPlayer链。

以下是核心方法的概述

.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以获取相关的工作示例。 希望这有帮助!

-Update 12/7/2015我现在有一个Swift源代码示例view here

答案 1 :(得分:13)

我通过将AVPlayer添加到我的本地网址

file://使用本地网址
NSURL * localURL = [NSURL URLWithString:[@"file://" stringByAppendingString:YOUR_LOCAL_URL]];
AVPlayer * player = [[AVPlayer alloc] initWithURL:localURL];

答案 2 :(得分:3)

是的,可以将.mp3(或任何类型的文件)下载并保存到NSDocument目录中,然后您可以从中恢复并使用AVAudioPlayer播放。

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
  }

检索下载的音频和播放:

   NSString *docDir1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NSUserDomainMask, YES) objectAtIndex:0];

   NSString *myfilepath = [docDir1 stringByAppendingPathComponent:YourAudioNameinNSDOCDir];

   NSLog(@”url:%@”,myfilepath);

   NSURL *AudioURL = [[[NSURLalloc]initFileURLWithPath:myfilepath]autorelease];

只需编写代码即可使用AudioURL播放音频

我想知道你是否在这方面有任何澄清。

谢谢

答案 3 :(得分:3)

试试这个

NSString*thePath=[[NSBundle mainBundle] pathForResource:@"yourVideo" ofType:@"MOV"];
NSURL*theurl=[NSURL fileURLWithPath:thePath];

答案 4 :(得分:1)

使用Avplayer播放歌曲非常困难,为什么你不使用MPMoviePlayerController播放器。我从文档目录播放歌曲。我发布了一个代码请参考。工作正常。还有你直接从url live。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *publicDocumentsDir = [paths objectAtIndex:0];   
NSString *dataPath = [publicDocumentsDir stringByAppendingPathComponent:@"Ringtone"];
NSString *fullPath = [dataPath stringByAppendingPathComponent:[obj.DownloadArray objectAtIndex:obj.tagvalue]];
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:NO];


NSURL *url = [NSURL fileURLWithPath:fullPath];

videoPlayer =[[MPMoviePlayerController alloc] initWithContentURL: url];
[[videoPlayer view] setFrame: [self.view bounds]]; 
[vvideo addSubview: [videoPlayer view]];


videoPlayer.view.frame=CGRectMake(0, 0,260, 100);
videoPlayer.view.backgroundColor=[UIColor clearColor];
videoPlayer.controlStyle =   MPMovieControlStyleFullscreen;
videoPlayer.shouldAutoplay = YES;  
[videoPlayer play];
videoPlayer.repeatMode=YES;


NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:@selector(moviePlayerEvent:) name:MPMoviePlayerLoadStateDidChangeNotification object:videoPlayer];


/*  NSNotificationCenter *notificationCenter1 = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:@selector(moviePlayerEvent1:) name:MPMoviePlaybackStateStopped object:videoPlayer];
*/
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(playbackStateChange:)
                                             name:MPMoviePlayerLoadStateDidChangeNotification
                                           object:videoPlayer];
}

-(void)playbackStateChange:(NSNotification*)notification{

if([[UIApplication sharedApplication]respondsToSelector:@selector(setStatusBarHidden: withAnimation:)])
  { 
      [[UIApplication sharedApplication] setStatusBarHidden:NO 
                                            withAnimation:UIStatusBarAnimationNone];
   }
  else 
   {

       [[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
   }
}

 -(void)moviePlayerEvent:(NSNotification*)aNotification{


   [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];


}

  -(void)moviePlayerEvent1:(NSNotification*)aNotification{

[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];

 }

答案 5 :(得分:0)

快速本地播放版本,假设我的捆绑包中有文件“ 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;
}

有关播放器视图或播放远程URL的详细信息,请参见here