iOS streaming media player and download Han Junqiang's Blog

Source: Internet
Author: User
Tags file copy uikit

Daily Update Attention :http://weibo.com/hanjunqiang Sina Weibo

Introduction to streaming media in iOS: between the download local playback and live streaming media, a form of play, download local playback must all download the file before it can play, and progressive download does not have to wait until all the download is complete before playing, it can be downloaded while playing, after the completion of the content, The entire file will be saved on your phone.

Live Streaming media

Real-time streaming is the one side of the receiving packet playback, the local does not keep the file copy, live streaming is always real-time transmission, real-time live broadcast, support random access, users can fast forward or rewind to view the front or back of the content. Real-time streaming media transmission must ensure that the transmission speed of the packet is greater than the speed of the file, or the user will see a video pause. Video quality degrades when the network is plugged, so it's better to ensure that the quality of the video is progressively downloaded.

Here is my pro-test streaming media playback and download tutorial:

Daily Update Attention :http://weibo.com/hanjunqiang Sina Weibo

=====================================================

1. Interface Construction ()

2. Third-party helper class (required to be able to interact with Weibo or private messages i) daily update attention :http://weibo.com/hanjunqiang Sina Weibo

: http://pan.baidu.com/s/1hrvqXA8

Daily Update Attention :http://weibo.com/hanjunqiang Sina Weibo

3. Start Project-header file and related macros


Daily Update Attention :http://weibo.com/hanjunqiang Sina Weibo

Lo_viewcontroller.h

#import <UIKit/UIKit.h> #import <MediaPlayer/MediaPlayer.h> #import "M3U8Handler.h" #import " VideoDownloader.h "#import" HTTPServer.h "@interface lo_viewcontroller:uiviewcontroller<m3u8handlerdelegate, Videodownloaddelegate> @property (nonatomic, Strong) httpserver * httpserver; @property (nonatomic, Strong) VideoDownloader *downloader; @end

Lo_viewcontroller.m

#import "Lo_viewcontroller.h" @interface Lo_viewcontroller () @property (weak, nonatomic) Iboutlet Uiprogressview * Progressview; @property (weak, nonatomic) Iboutlet UILabel *progresslabel; @property (weak, nonatomic) Iboutlet UIButton * Downloadbutton, @property (weak, nonatomic) Iboutlet UIButton *clearbutton; @end @implementation lo_viewcontroller-(        void) viewdidload{[Super viewdidload];//do any additional setup after loading the view, typically from a nib.        Open the local server [self openhttpserver]; if ([[[[Nsuserdefaults Standarduserdefaults] objectforkey:@ "Isdownload"] boolvalue]) {[Self.downloadbutton setTitle        : @ "completed" forstate:uicontrolstatenormal];        self.downloadButton.enabled = NO;        self.clearButton.enabled = YES;        M3u8handler *handler = [[M3u8handler alloc] init];        [Handler praseurl:[nsstring stringwithformat:@ "Http://v.youku.com/player/getM3U8/vid/XNjUxMTE4NDAw/type/mp4"];        Handler.playlist.uuid = @ "Xnjuxmte4ndaw"; Self.downloadeR = [[VideoDownloader alloc]initwithm3u8list:handler.playlist]; [Self.downloader addobserver:self forkeypath:@ "Clearcaches" options:nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold Context:nil]; Determine whether to clean up the cache}}

#pragma mark-Open the local server

-(void) openhttpserver{    self.httpserver = [[Httpserver alloc] init];    [Self.httpserver settype:@ "_http._tcp."];  Set the service type    [Self.httpserver setport:12345];//Set server port            //Get local Library/cache path under downloads path    NSString * Webpath = [Klibrarycache stringbyappendingpathcomponent:kpathdownload];    NSLog (@ "-------------\nsetting document Root:%@\n", Webpath);    Set the server path [Self.httpserver Setdocumentroot:webpath];    Nserror *error;    if (![ Self.httpserver Start:&error]) {        NSLog (@ "-------------\nerror starting HTTP Server:%@\n", error);}}

#pragma mark-Clean Cache-(ibaction) Clearcaches: (ID) Sender {    [Self.downloader cleandownloadfiles];}

#pragma mark-stream Media Player online

-(Ibaction) Playstreamingmedia: (ID) Sender {//Youku video m3u8 new address format as follows: Http://pl.youku.com/playlist/m3u8?vid=XNjUxMTE4NDAw &type=mp4//If the above link is not available, then use this link http://v.youku.com/player/getM3U8/vid/XNjUxMTE4NDAw/type/mp4, if two connections are not available, So very big may be Youku server hangs up//if the above two formats are not, consider using this format, of course, if this format is not, is the above, or directly change the corresponding m3u8 address http://pl.youku.com/playlist/m3u8? vid=162779600&ts=1407469897&ctype=12&token=3357&keyframe=1&sid=640746989782612d6cc70& ev=1&type=mp4&ep=dcauhu2lx8yj4ivdjj8bmyqxj3apxp8m9bicinrianqns%2b24&oip=2043219268 NSURL *url = [[ Nsurl Alloc] initwithstring:@ "http://pl.youku.com/playlist/m3u8?vid=162779600&ts=1407469897&ctype=12 &token=3357&keyframe=1&sid=640746989782612d6cc70&ev=1&type=flv&ep=    dcauhu2lx8yj4ivdjj8bmyqxj3apxp8m9bicinrianqns%2b24&oip=2043219268 "];        Mpmovieplayerviewcontroller *player = [[Mpmovieplayerviewcontroller alloc] initwithcontenturl:url]; [Self presentmovieplayerviewcontrolleranimated:Player]; }
Daily Update Attention :http://weibo.com/hanjunqiang Sina Weibo
#pragma mark-Video download

-(Ibaction) Downloadstreamingmedia: (ID) Sender {UIButton *downloadbutton = sender;    Get local Library/cache path nsstring *localdownloadspath = [Klibrarycache stringbyappendingpathcomponent:kpathdownload];    Get the video local path nsstring *filepath = [Localdownloadspath stringbyappendingpathcomponent:@ "xnjuxmte4ndaw/movie.m3u8"];        Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager]; Determines if the video cache is complete, and if complete, plays the local cache if ([FileManager Fileexistsatpath:filepath]) {[Downloadbutton settitle:@ ' completed ' Forstat        E:uicontrolstatenormal];        downloadbutton.enabled = NO;        }else{M3u8handler *handler = [[M3u8handler alloc] init];        Handler.delegate = self; Parse m3u8 video address [handler praseurl:@ "http://pl.youku.com/playlist/m3u8?vid=162779600&ts=1407469897&ctype=12& amp;token=3357&keyframe=1&sid=640746989782612d6cc70&ev=1&type=flv&ep=                dcauhu2lx8yj4ivdjj8bmyqxj3apxp8m9bicinrianqns%2b24&oip=2043219268 "]; // Turn on the network indicator [[uiapplication sharedapplication] setnetworkactivityindicatorvisible:yes]; }}

#pragma mark-Play local cache video

-(Ibaction) playvideofromlocal: (ID) Sender {nsstring * playurl = [NSString stringwithformat:@] http://127.0.0.1:1234    5/xnjuxmte4ndaw/movie.m3u8 "];        NSLog (@ "Local Video address-----%@", playurl);    Get local Library/cache path nsstring *localdownloadspath = [Klibrarycache stringbyappendingpathcomponent:kpathdownload];    Get the video local path nsstring *filepath = [Localdownloadspath stringbyappendingpathcomponent:@ "xnjuxmte4ndaw/movie.m3u8"];        Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager]; Determines if the video cache is complete, and if done, plays the local cache if ([FileManager Fileexistsatpath:filepath]) {Mpmovieplayerviewcontroller *playerview        Controller =[[mpmovieplayerviewcontroller Alloc]initwithcontenturl:[nsurl Urlwithstring:playurl]];    [Self presentmovieplayerviewcontrolleranimated:playerviewcontroller]; } else{Uialertview *alertview = [[Uialertview alloc] initwithtitle:@ "Sorry" message:@ "current video not cached" Delegate:self CA        ncelbuttontitle:@ "OK" otherbuttontitles:nil, nil]; [Alertview Show]; }} #pragma mark-#pragma mark-Video parsing complete-(void) prasem3u8finished: (m3u8handler*) handler{handler.playlist.uuid = @ "XNJUXMT    E4ndaw ";    Self.downloader = [[VideoDownloader alloc]initwithm3u8list:handler.playlist]; [Self.downloader addobserver:self forkeypath:@ "currentprogress" options:nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold Context:nil]; Sets the progress that the observer uses to get the current download [Self.downloader addobserver:self forkeypath:@ "clearcaches" options: Nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold Context:nil];    Determines whether to clean up the cache self.downloader.delegate = self; [Self.downloader Startdownloadvideo]; Start Download}
Daily Update Attention:Http://weibo.com/hanjunqiangSina Micro-blog

#pragma mark-Monitor the download progress display/cache cleanup through the viewer

-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *)        context{if ([KeyPath isequaltostring:@ "Clearcaches"]) {self.downloadButton.enabled = YES;        [Self.downloadbutton settitle:@ "Download" forstate:uicontrolstatenormal];        self.clearButton.enabled = NO;        [[Nsuserdefaults Standarduserdefaults] setobject:[nsnumber Numberwithbool:no] forkey:@ "IsDownload"];        [[Nsuserdefaults standarduserdefaults] synchronize];        self.progressView.progress = 0.0;    Self.progressLabel.text = [NSString stringwithformat:@ "%.2f%%", 0.0]; }else{Self.progressLabel.text = [NSString stringwithformat:@ "%.2f%%", [Change objectforkey:@ "new"] Floatval        UE]];        self.progressView.progress = [Change objectforkey:@ "new"] floatvalue]; if (self.progressView.progress = = 1) {[[Nsuserdefaults standarduserdefaults] Setobject:[nsnumber Numberwithboo            L:yes] forkey:@ "Isdownload"]; [SELf.downloadbutton settitle:@ "completed" forstate:uicontrolstatenormal];            [[Nsuserdefaults standarduserdefaults] synchronize];            self.clearButton.enabled = YES;        self.downloadButton.enabled = NO; }    }    }
Daily Update Attention:Http://weibo.com/hanjunqiangSina Micro-blog
#pragma mark-Video parsing failed-(void) prasem3u8failed: (m3u8handler*) handler{    NSLog (@ "video parsing failed-failed-%@", handler);    Uialertview *alertview = [[Uialertview alloc] initwithtitle:@ "Oh, no~

iOS streaming media player and download Han Junqiang's Blog

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.