在iOS应用中使用本地视频文件(xcode) [英] Using local video files in iOS app (xcode)

查看:112
本文介绍了在iOS应用中使用本地视频文件(xcode)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在iOS App中播放视频文件的最佳方法.我的应用程序目前正在开发中,大约有50个视频(每个30秒长)和简短的教程.如果可能的话,我希望它们都在本地,以便用户在没有互联网连接的情况下可以观看视频.我在堆栈溢出时找不到类似的问题(也许我找错了部分,如果我写错了,请纠正我).

I'm looking for the best way to play back video files in my iOS App. My app is currently in development and there will be around 50 videos (each 30 seconds long) with short tutorials. If possible I want them all local, so users can watch the videos when they do not have an internet connection. I could not find a similar question on stack overflow (maybe I'm looking in the wrong section, please correct me if I'm wrong).

所以我在考虑2种不同的选择:

So I was thinking about 2 different options:

  • 用户从商店下载应用程序,包括视频
  • 用户下载不带视频的应用程序,并且首次使用该应用程序时必须先下载视频并保存 本地(永远)
  • User downloads app from store, including videos
  • User downloads app without the videos, and has to download the videos first when using the app for the first time and save them locally (forever)

如果有更好的选择,我也想认识他们! 因此,如果有人对此有经验,我将非常感谢您的帮助!谢谢

If there are better options, I would also like to know them! So if anyone has experience with this, I would really appreciate some help! Thanks

推荐答案

人们更喜欢离线模式.并希望他们在从Appstore下载应用程序时尽可能缩小应用程序的大小. 因此,我的建议是构建一个视频播放器,该视频播放器既可以选择在用户在线时流式传输文件,又可以离线播放可下载或缓存的文件..

as per the user point of view people prefer offline mode . and want app size to be as low as possible when they download the app from the Appstore. so my recommendation is to build a video player which have both option to stream file while user is online and play offline downloadable or cached files ..

一种方法是:

使用网络服务器

use a webserver

简单的Java服务器示例:
https://github.com/mooncatventures-group/StreamX
检查: http://www.onlinevideo. net/2011/05/streaming-vs-progressive-download-vs-adaptive-streaming/

simple java server example :
https://github.com/mooncatventures-group/StreamX
check : http://www.onlinevideo.net/2011/05/streaming-vs-progressive-download-vs-adaptive-streaming/

构建一个更好的应用程序使用户能够下载和存储应用程序内容更好 从应用商店下载应用之后. 应用应该可以选择删除应用下载的视频或清除缓存.

its better to build a app which give user the power to download and store app content after the app is been downloaded from app store . app should have option to delete app downloaded videos or to clear cache .

down是视频播放器的示例,它可以播放脱机和在线视频.

down is an example of video player which can play both offline and online video .


//CustomMoviePlayerViewController.h File 
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

@interface CustomMoviePlayerViewController : UIViewController 
{
    MPMoviePlayerController *mp;
    NSURL *movieURL;
}

- (id)initWithPath:(NSString *)moviePath;
- (id)initWithURL:(NSString *)moviePath;
- (void)readyPlayer;

@end

CustomMoviePlayerViewController.m文件

#import "CustomMoviePlayerViewController.h"

#pragma mark -
#pragma mark Compiler Directives & Static Variables

@implementation CustomMoviePlayerViewController

/*---------------------------------------------------------------------------
* 
*--------------------------------------------------------------------------*/
- (id)initWithPath:(NSString *)moviePath
{
    // Initialize and create movie URL
  if (self = [super init])
  {
      movieURL = [NSURL fileURLWithPath:moviePath];    
    [movieURL retain];
  }
    return self;
}
- (id)initWithURL:(NSString *)moviePath{
    // Initialize and create movie URL
    if (self = [super init])
    {
        movieURL = [NSURL URLWithString:moviePath];    
        [movieURL retain];
    }
    return self;

}

/*---------------------------------------------------------------------------
* For 3.2 and 4.x devices
* For 3.1.x devices see moviePreloadDidFinish:
*--------------------------------------------------------------------------*/
- (void) moviePlayerLoadStateChanged:(NSNotification*)notification 
{
    // Unless state is unknown, start playback
    if ([mp loadState] != MPMovieLoadStateUnknown)
  {
    // Remove observer
    [[NSNotificationCenter  defaultCenter] 
                                                    removeObserver:self
                                name:MPMoviePlayerLoadStateDidChangeNotification 
                                object:nil];

    // When tapping movie, status bar will appear, it shows up
    // in portrait mode by default. Set orientation to landscape
    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];

        // Rotate the view for landscape playback
      [[self view] setBounds:CGRectMake(0, 0, 480, 320)];
        [[self view] setCenter:CGPointMake(160, 240)];
        [[self view] setTransform:CGAffineTransformMakeRotation(M_PI / 2)]; 

        // Set frame of movieplayer
        [[mp view] setFrame:CGRectMake(0, 0, 480, 320)];

    // Add movie player as subview
      [[self view] addSubview:[mp view]];   

        // Play the movie
        [mp play];
    }
}

/*---------------------------------------------------------------------------
* For 3.1.x devices
* For 3.2 and 4.x see moviePlayerLoadStateChanged: 
*--------------------------------------------------------------------------*/
- (void) moviePreloadDidFinish:(NSNotification*)notification 
{
    // Remove observer
    [[NSNotificationCenter  defaultCenter] 
                                                    removeObserver:self
                            name:MPMoviePlayerContentPreloadDidFinishNotification
                            object:nil];

    // Play the movie
    [mp play];
}

/*---------------------------------------------------------------------------
* 
*--------------------------------------------------------------------------*/
- (void) moviePlayBackDidFinish:(NSNotification*)notification 
{    
  [[UIApplication sharedApplication] setStatusBarHidden:YES];

    // Remove observer
  [[NSNotificationCenter    defaultCenter] 
                                                removeObserver:self
                            name:MPMoviePlayerPlaybackDidFinishNotification 
                            object:nil];

    [self dismissModalViewControllerAnimated:YES];  
}

/*---------------------------------------------------------------------------
*
*--------------------------------------------------------------------------*/
- (void) readyPlayer
{
    mp =  [[MPMoviePlayerController alloc] initWithContentURL:movieURL];

  if ([mp respondsToSelector:@selector(loadState)]) 
  {
    [mp setMovieSourceType:MPMovieSourceTypeFile];
    // Set movie player layout
    [mp setControlStyle:MPMovieControlStyleFullscreen];
    [mp setFullscreen:YES];

        // May help to reduce latency
        [mp prepareToPlay];

        // Register that the load state changed (movie is ready)
        [[NSNotificationCenter defaultCenter] addObserver:self 
                       selector:@selector(moviePlayerLoadStateChanged:) 
                       name:MPMoviePlayerLoadStateDidChangeNotification 
                       object:nil];
    }  
  else
  {
    // Register to receive a notification when the movie is in memory and ready to play.
    [[NSNotificationCenter defaultCenter] addObserver:self 
                         selector:@selector(moviePreloadDidFinish:) 
                         name:MPMoviePlayerContentPreloadDidFinishNotification
                         object:nil];
  }

  // Register to receive a notification when the movie has finished playing. 
  [[NSNotificationCenter defaultCenter] addObserver:self 
                        selector:@selector(moviePlayBackDidFinish:) 
                        name:MPMoviePlayerPlaybackDidFinishNotification 
                        object:nil];
}

/*---------------------------------------------------------------------------
* 
*--------------------------------------------------------------------------*/
- (void) loadView
{
  [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
    [[self view] setBackgroundColor:[UIColor blackColor]];
}

/*---------------------------------------------------------------------------
*  
*--------------------------------------------------------------------------*/
- (void)dealloc 
{
    [mp release];
  [movieURL release];
    [super dealloc];
}

@end

当您单击TableListView单元格时,使播放器视图可见.

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@",[documentsDirectory stringByAppendingPathComponent:[item valueForKey:@"URL"]]];
        bool b=[[NSFileManager defaultManager] fileExistsAtPath:filePath];

CustomMoviePlayerViewController *moviePlayer;

if (b) {
    moviePlayer = [[[CustomMoviePlayerViewController alloc] initWithPath:filePath] autorelease];
    [self presentModalViewController:moviePlayer animated:YES];
    [moviePlayer readyPlayer];
}else{
    NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
    NSString *strURL = [NSString stringWithFormat:[item valueForKey:@"URL"]];
    moviePlayer = [[[CustomMoviePlayerViewController alloc] initWithURL:strURL] autorelease];
    [self presentModalViewController:moviePlayer animated:YES];
    [moviePlayer readyPlayer];
}

制作一个URL下载器.将文件保存在.

https://github.com/AFNetworking/AFNetworking

-(void)downloadFile:(NSString *)UrlAddress
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlAddress]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *fileName = UrlAddress;

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    NSLog(@"Download = %f", (float)totalBytesRead / totalBytesExpectedToRead);

}];
[operation start];
}

因此,这将允许您保存文件并播放+播放应用程序中已经存在的预加载文件.

So this will allow you to save File and play + play preloaded files which are already present within your app.

这篇关于在iOS应用中使用本地视频文件(xcode)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆