如何使用URLSession下载视频,保存并在appcelerator钛中播放?

时间:2015-09-18 05:16:41

标签: ios nsurlsession titanium-alloy appcelerator-mobile titanium-modules

我正在尝试使用URLSession下载并保存视频,然后在视频播放器中播放。但不知怎的,它没有播放,而是它崩溃了应用程序。这是代码。我已尝试使用nativePathgetNativePath()file.resolve()几乎所有内容来阅读文件的确切路径,但似乎没有任何效果。看看代码并提出解决方案。这适用于iOS。 (iOS版本8.4)

更新代码:

    var args = arguments[0] || {};

    var vidWin = $.winTestVideo;
    var isDownloading = false;

    var urlSession = require("com.appcelerator.urlSession");
    var downloadSession;

    var urlArray = ["http://www.kaltura.com/p/{PARTNERID}/sp/{SUBPARTNERID}/playManifest/entryId/{entryId}/format/applhttp/protocol/http/flavorId/{flavorId}/video.mp4",
"http://www.kaltura.com/p/{PARTNERID}/sp/{SUBPARTNERID}/playManifest/entryId/{entryId}/format/applhttp/protocol/http/flavorId/{flavorId}/video.mp4"];

    var urlArrIndex = 0;
    var progress;
    var videoPlayer;
    var imageUrl = 'http://dreamatico.com/data_images/rose/rose-4.jpg';
    //'http://cdn.playbuzz.com/cdn/5d41f0c6-2688-47fe-85cf-82890ef6d91d/45611be8-42f9-4d02-9b63-f7195c0dc18c_560_420.jpg';
    var img;
    function onLoad() {
        Alloy.Globals.CurrentWindowName = 'testvideoplayer';
        var triggerBtn = Ti.UI.createButton({
            top : 10,
            width : Ti.UI.FILL,
            height : 40,
            backgroundColor : "#cccccc",
            color : "#000000",
            title : "Download Videos"
        });
        vidWin.add(triggerBtn);
        triggerBtn.addEventListener('click', downloadVideoBackround2);

        progress = Titanium.UI.createProgressBar({
            width : 200,
            height : 20,
            min : 0,
            max : 1,
            value : 0,
            top : 60,
            backgroundColor : "#0000ff",
            style : Ti.UI.iPhone.ProgressBarStyle.BAR,

        });

        vidWin.add(progress);

        img = Ti.UI.createImageView({
            width : 100,
            height : 100,
            backgroundColor : "#cccccc"
        });
        //vidWin.add(img);

        //videoPlayer.play();

    }

    function createVideoPlayer() {
        videoPlayer = Ti.Media.createVideoPlayer({
            width : Ti.UI.FILL,
            height : 240,
            top : 100,
            mediaControlStyle : Titanium.Media.VIDEO_CONTROL_DEFAULT,
            scalingMode : Titanium.Media.VIDEO_SCALING_ASPECT_FIT,
            backgroundColor : "#000000",

        });
        vidWin.add(videoPlayer);
        videoPlayer.removeEventListener('playbackstate', playbackStateEventListener);
        videoPlayer.addEventListener('playbackstate', playbackStateEventListener);
    }

    // Require in the urlSession module
    var urlSession = require("com.appcelerator.urlSession");
    var session;
    // App UI

    function playbackStateEventListener(evt) {
        Ti.API.error("PlaybackStateEventListener  : " + JSON.stringify(evt));
    }

    function downloadVideoBackround2(evt){
        // Create a session configuration
        // The string parameter is an arbitrary string used to identify the session in events
        var sessionConfig = urlSession.createURLSessionBackgroundConfiguration("com.appcelerator.test");
        // Create a session
        session = urlSession.createURLSession(sessionConfig);
        // Create a background download task to get the asset with the URL
        urlSession.backgroundDownloadTaskWithURL(session,urlArray[0].replace('applhttp','url'));
        progress.show();
    }

    // Monitor this event to receive updates on the progress of the download
    Ti.App.iOS.addEventListener("downloadprogress", function(e) {
        // Update the progress indicator
        Ti.API.error("DOWNLOAD PROGRESS : " + e.totalBytesWritten + "/" + e.totalBytesExpectedToWrite);
        progress.value = (e.totalBytesWritten / e.totalBytesExpectedToWrite);
    });

    // Monitor this event to know when the download completes
    Ti.App.iOS.addEventListener("downloadcompleted", function(e) {
        Ti.API.error("download completed " + JSON.stringify(e));
        // Update the image
        try {

            var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, 'myplvideo.mp4');
            if (!file.exists()) {
                file.createFile();
            }
            file.write(e.data);
            Ti.API.error('data : ' + e.data.length);
            Ti.API.error('file : ' + file.nativePath);
            Ti.API.error('file resolve path :' + file.resolve());
            progress.hide();

            // Notify the user the download is complete if the application is in the background
            setTimeout(function() {

                //videoPlayer.media = file;
                createVideoPlayer();
                videoPlayer.media = file;
                urlSession.finishTasksAndInvalidate(session);
                //videoPlayer.play();
            }, 3000);

            //alert('Download completed!');
            /*
             Ti.App.iOS.scheduleLocalNotification({
             alertAction : "update",
             // Alert will display the following message
             alertBody : "Download was successfull",
             // The badge value in the icon will be changed to 1
             badge : 1,
             // Alert will be sent in three seconds
             date : new Date(new Date().getTime() + 3000),
             });*/

        } catch(ex) {
            Ti.API.error('download completed : ' + ex);
        }
    });
    // Monitor this event to know when all session tasks have completed
    Ti.App.iOS.addEventListener('sessioncompleted', function(e) {
        try {

            Ti.API.error("sessioncompleted " + JSON.stringify(e));
            if (e.success) {
                //alert("Downloads completed successfully.");
            }
        } catch(ex) {
            Ti.API.error('Exception session completed : ' + ex);
        }
    });

当我将file分配给videoPlayer的{​​{1}}媒体资源时,应用会崩溃。但是当我使用HttpClient下载文件时,它工作正常。不确定为什么会发生这种情况,因为我无法在日志中看到任何错误。

以下是日志。我使用[Error]突出显示重要的日志记录。

media

1 个答案:

答案 0 :(得分:0)

我的快速猜测是你有竞争条件。在你的setTimeout里面,你从来没有真正检查文件是否已被写入,就像你完成下载一样,假设此时3s足够长。

// Notify the user the download is complete if the application is in the background
setTimeout(function() {
  //videoPlayer.media = file;
  createVideoPlayer();
  videoPlayer.media = file;
  urlSession.finishTasksAndInvalidate(session);
  //videoPlayer.play();
}, 3000);

此外,设备或模拟器的xcode日志应该告诉你哪些/什么崩溃(这些可能并不总是出现在钛日志中)