簡體   English   中英

在iOS應用中使用本地視頻文件(xcode)

[英]Using local video files in iOS app (xcode)

我正在尋找在iOS應用中播放視頻文件的最佳方式。 我的應用程序目前正在開發中,將有大約50個視頻(每個30秒長)和簡短的教程。 如果可能的話,我希望它們都是本地的,因此用戶可以在沒有互聯網連接的情況下觀看視頻。 我在堆棧溢出時找不到類似的問題(也許我正在查找錯誤的部分,如果我錯了請糾正我)。

所以我在考慮兩種不同的選擇:

  • 用戶從商店下載應用,包括視頻
  • 用戶在沒有視頻的情況下下載應用程序,並且必須在首次使用該應用程序時首先下載視頻並在本地保存(永久)

如果有更好的選擇,我也想知道它們! 所以,如果有人有這方面的經驗,我真的很感激一些幫助! 謝謝

根據用戶的觀點,人們更喜歡離線模式。 並希望從Appstore下載應用程序時,應用程序大小盡可能低。 所以我的建議是建立一個視頻播放器,它既可以在用戶上線時播放文件,也可以播放離線下載或緩存文件。

一種方法是:

使用網絡服務器

簡單的java服務器示例:
https://github.com/mooncatventures-group/StreamX
檢查: http//www.onlinevideo.net/2011/05/streaming-vs-progressive-download-vs-adaptive-streaming/

更好地構建一個應用程序,使用戶能夠在從應用程序商店下載應用程序后下載和存儲應用程序內容。 應該可以選擇刪除應用下載的視頻或清除緩存。

down是一個可以播放離線和在線視頻的視頻播放器的例子。

制作自定義電影播放器​​..


//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];
}

制作網址下載器。 保存文件。

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

因此,這將允許您保存文件並播放+播放已存在於您的應用程序中的預加載文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM