2014-10-30 255 views
2

我試圖在Android上傳視頻到YouTube。 我希望用戶使用GoogleAuthUtil通過他的Google帳戶進行驗證,並且工作正常。然後我有用戶名和令牌,也加載了uriFile。Youtube上傳視頻Android

我想要做的最後一步是上傳到Youtube。要做到這一點,我跟着這個代碼https://code.google.com/p/ytd-android/source/browse/trunk/?r=38

我在我的代碼的問題是這部分:

File file = new File(fileUri.getPath()); 
long mFileSize = file.length(); 
GoogleCredential credential = new GoogleCredential(); 
credential.setAccessToken(mToken); 

HttpTransport httpTransport = new NetHttpTransport(); 
JsonFactory jsonFactory = new JacksonFactory(); 

YouTube youtube = 
     new YouTube.Builder(httpTransport, jsonFactory, credential).setApplicationName(
       "fanscup").build(); 

InputStream fileInputStream = null; 
try { 
    mFileSize = getContentResolver().openFileDescriptor(fileUri, "r").getStatSize(); 
    fileInputStream = getContentResolver().openInputStream(fileUri); 
} catch (FileNotFoundException e) { 
    Log.e(getApplicationContext().toString(), e.getMessage()); 
} 
ResumableUpload.upload(youtube, fileInputStream, mFileSize, getApplicationContext()); 

,當我嘗試上傳我得到這個錯誤的視頻:

Uncaught handler: thread main exiting due to uncaught exception

java.io.FileNotFoundException: /dev/kmsg (Permission denied)

java.io.IOException: Permission denied

resizing JitTable from 4096 to 8192

FATAL EXCEPTION: main

java.lang.NoClassDefFoundError: com.google.api.client.util.Clock

at com.google.api.client.auth.oauth2.Credential. (Credential.java:200)

at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.(GoogleCredential.java:187)

at com.library_fanscup.UploadActivity$1.onPostExecute(UploadActivity.java:483)

at com.library_fanscup.UploadActivity$1.onPostExecute(UploadActivity.java:1)

at android.os.AsyncTask.finish(AsyncTask.java:417)

at android.os.AsyncTask.access$300(AsyncTask.java:127)

at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)

at android.os.Handler.dispatchMessage(Handler.java:99)

at android.os.Looper.loop(Looper.java:130) at android.app.ActivityThread.main(ActivityThread.java:3683)

at java.lang.reflect.Method.invokeNative(Native Method)

at java.lang.reflect.Method.invoke(Method.java:507)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653)

at dalvik.system.NativeStart.main(Native Method)

exception :java.io.FileNotFoundException: /dev/kmsg (Permission denied)

exception :java.io.FileNotFoundException: /dev/kmsg (Permission denied)

java.io.FileNotFoundException: /data/plog.log (Permission denied)

燦有人幫助我?有任何想法嗎?

回答

0

You can use below class

公共靜態無效uploadVideo(絃樂味精,最終語境上下文){// 列表範圍= Lists.newArrayList( 「https://www.googleapis.com/auth/youtube.upload」);

HttpTransport transport = AndroidHttp.newCompatibleTransport(); 
    JsonFactory jsonFactory = new GsonFactory(); 
    GoogleCredential googleCredential = 
      new GoogleCredential.Builder() 
        .setTransport(transport) 
        .setJsonFactory(jsonFactory) 
        .setClientSecrets("client_id", "client_scretekey").build(); 
    googleCredential.setAccessToken("Access_token"); 
    googleCredential.setRefreshToken("refresh_token"); 

    String appName =""; 
    final YouTube youtube = 
      new YouTube.Builder(transport, jsonFactory, googleCredential).setApplicationName(
        appName).build(); 

    InputStream fileInputStream = null; 
    long fileSize = 0; 
    File filem=new File(msg); 
    Uri mFileUri=Uri.fromFile(filem); 
    try { 
     fileSize = context.getContentResolver().openFileDescriptor(mFileUri, "r").getStatSize(); 
     fileInputStream = context.getContentResolver().openInputStream(mFileUri); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

    final NotificationManager notifyManager = 
      (NotificationManager)context. getSystemService(Context.NOTIFICATION_SERVICE); 
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 
    builder.setContentTitle("Uploading Video") 
      .setContentText("Live Streaming") 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .build(); 

    String videoId = null; 
    try { 
     // Add extra information to the video before uploading. 
     Video videoObjectDefiningMetadata = new Video(); 
     VideoStatus status = new VideoStatus(); 
     status.setPrivacyStatus("public"); 

     videoObjectDefiningMetadata.setStatus(status); 

     // We set a majority of the metadata with the VideoSnippet object. 
     VideoSnippet snippet = new VideoSnippet(); 

     Calendar cal = Calendar.getInstance(); 
     snippet.setTitle("Live Streaming Upload On " + cal.getTime()); 
     snippet.setDescription("Live Streaming Upload video on youtube " 
       + "on " + cal.getTime()); 
     // Set your keywords. 
     snippet.setTags(Arrays.asList("Android client 1", 
       Upload.generateKeywordFromPlaylistId("client_id"))); 
     // Set completed snippet to the video object. 
     videoObjectDefiningMetadata.setSnippet(snippet); 
     InputStreamContent mediaContent = 
       new InputStreamContent(VIDEO_FILE_FORMAT, new BufferedInputStream(fileInputStream)); 
     mediaContent.setLength(fileSize); 
     YouTube.Videos.Insert videoInsert = 
       youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, 
         mediaContent); 


       // Set the upload type and add event listener. 
       MediaHttpUploader uploader = videoInsert.getMediaHttpUploader(); 

       uploader.setDirectUploadEnabled(false); 

       final long FileSize = fileSize; 
       MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() { 
        public void progressChanged(MediaHttpUploader uploader) throws IOException { 
         switch (uploader.getUploadState()) { 
          case INITIATION_STARTED: 
           builder.setContentText(context.getString(R.string.initiation_started)).setProgress((int) FileSize, 
             (int) uploader.getNumBytesUploaded(), false); 

           notifyManager.notify((int)uniqueId, builder.build()); 
           break; 
          case INITIATION_COMPLETE: 
           builder.setContentText(context.getString(R.string.initiation_completed)).setProgress((int) FileSize, 
             (int) uploader.getNumBytesUploaded(), false); 
           notifyManager.notify((int)uniqueId, builder.build()); 
           break; 
          case MEDIA_IN_PROGRESS: 
           builder 
             .setContentTitle(context.getString(R.string.youtube_upload) + 
               (int) (uploader.getProgress() * 100) + "%") 
             .setContentText(context.getString(R.string.upload_in_progress)) 
             .setProgress((int) FileSize, (int) uploader.getNumBytesUploaded(), false); 
           notifyManager.notify((int)uniqueId, builder.build()); 
           break; 
          case MEDIA_COMPLETE: 
           builder.setContentTitle(context.getString(R.string.yt_upload_completed)) 
             .setContentText(context.getString(R.string.upload_completed)) 
             // Removes the progress bar 
             .setProgress(0, 0, false); 
           notifyManager.notify((int)uniqueId, builder.build()); 

          case NOT_STARTED: 
           Log.d(this.getClass().getSimpleName(),context.getString(R.string.upload_not_started)); 
           break; 
         } 
        } 
       }; 
       uploader.setProgressListener(progressListener); 

     // Execute upload. 
     Video returnedVideo = videoInsert.execute(); 
     Log.d(TAG, "Video upload completed"); 

     videoId = returnedVideo.getId(); 
     Log.d(TAG, String.format("videoId = [%s]", videoId)); 
     //delete video after video upload completed 

    } catch (final GooglePlayServicesAvailabilityIOException availabilityException) { 
     Log.e(TAG, "GooglePlayServicesAvailabilityIOException", availabilityException); 
     notifyFailedUpload(context, context.getString(R.string.cant_access_play), notifyManager, builder); 
    } catch (UserRecoverableAuthIOException userRecoverableException) { 
     Log.i(TAG, String.format("UserRecoverableAuthIOException: %s", 
       userRecoverableException.getMessage())); 
     requestAuth(context, userRecoverableException); 
    } catch (IOException e) { 
     Log.e(TAG, "IOException", e); 
     notifyFailedUpload(context,context.getString(R.string.please_try_again), notifyManager, builder); 
    } 

}