Stream video while downloading iOS

后端 未结 3 1189
故里飘歌
故里飘歌 2021-01-30 05:44

I am using iOS 7 and I have a .mp4 video that I need to download in my app. The video is large (~ 1 GB) which is why it is not included as part of the app. I want the user to be

3条回答
  •  走了就别回头了
    2021-01-30 06:19

    I figured out how to do this, and it is much simpler than my original idea.

    First, since my video is in .mp4, the MPMoviePlayerViewController or AVPlayer class can play it directly from a web server - I don't need to implement anything special and they can still seek to any point in the video. This must be part of how the .mp4 encoding works with the movie players. So, I just have the raw file available on the server - no special headers required.

    Next, when the user decides to play the video I immediately start playing the video from the server URL:

    NSURL *url=[NSURL fileURLWithPath:serverVidelFileURLString];
    controller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    controller.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
    [self presentMoviePlayerViewControllerAnimated:controller];
    

    This makes it so the user can watch the video and seek to any location they want. Then, I start downloading the file manually using NSURLConnection like I had been doing above, except now I am not streaming the file, I just download it directly. This way I don't need the custom header since the file size is included in the HTTP response.

    When my background download completes, I switch the playing item from the server URL to the local file. This is important for network performance because the movie players only download a few seconds ahead of what the user is watching. Being able to switch to the local file as soon as possible is key to avoid downloading too much duplicate data:

    NSTimeInterval currentPlaybackTime = videoController.moviePlayer.currentPlaybackTime;
    
    [controller.moviePlayer setContentURL:url];
    [controller.moviePlayer setCurrentPlaybackTime:currentPlaybackTime];
    [controller.moviePlayer play];
    

    This method does have the user downloading two video files at the same time initially, but initial testing on the network speeds my users will be using shows it only increases the download time by a few seconds. Works for me!

提交回复
热议问题