How to upload video to youtube from my app? - android

In my app : I wayt to pick a video from gallery and upload it to
youtube as unlisted with title, description.I got token.But idk how to
send post request.Any advice or sample code please ?

Please check this code:
// Sample java code for videos.insert
public static void main(String[] args) throws IOException {
try {
YouTube youtube = getYouTubeService();
String mime_type = "video/*";
String media_filename = "sample_video.flv";
HashMap<String, String> parameters = new HashMap<>();
parameters.put("part", "snippet,status");
Video video = new Video();
VideoSnippet snippet = new VideoSnippet();
snippet.set("categoryId", "22");
snippet.set("description", "Description of uploaded video.");
snippet.set("title", "Test video upload");
VideoStatus status = new VideoStatus();
status.set("privacyStatus", "private");
video.setSnippet(snippet);
video.setStatus(status);
InputStreamContent mediaContent = new InputStreamContent(mime_type,
ApiExample.class.getResourceAsStream(media_filename));
YouTube.Videos.Insert videosInsertRequest = youtube.videos().insert(parameters.get("part").toString(), video, mediaContent);
MediaHttpUploader uploader = videosInsertRequest.getMediaHttpUploader();
Video response = videosInsertRequest.execute();
System.out.println(response);
}
}
More info: YouTube Developer Documentation

Related

How can I list videos in android app using YouTube API in Android Studio

How do I list videos from a YouTube channel using YouTube API? I've created a project, I have the YouTubePlayerApi in my project and I have a API key, but I can't find a tutorial that shows how to use it. The tutorials I've seen have either been inaccuarate or really hard to follow along and understand.
You can check the Java sample in Videos.list:
// Sample java code for videos.list
public static void main(String[] args) throws IOException {
YouTube youtube = getYouTubeService();
try {
HashMap<String, String> parameters = new HashMap<>();
parameters.put("part", "snippet,contentDetails,statistics");
parameters.put("id", "Ks-_Mh1QhMc");
YouTube.Videos.List videosListByIdRequest = youtube.videos().list(parameters.get("part").toString());
if (parameters.containsKey("id") && parameters.get("id") != "") {
videosListByIdRequest.setId(parameters.get("id").toString());
}
VideoListResponse response = videosListByIdRequest.execute();
System.out.println(response);
}
}

Rotate video with Mp4parser

I need to rotate a video to adjust some of my needs. I'll explain the details on the following list.
I'm creating a Vine like app. I have to record video segments and then merge all the parts into just one file. I'm doing this without issue on an Android app using mp4 parser library with last version 1.0-RC-26 using the example provided on their website: here
The append video example works fine if all the videos have the same orientation but I discovered some issues recording video from the front camera so the quick solution was to set the video orientation recording on 270. The bad part on this solution is that the segment with this orientation appear with the wrong orientation on the merged video.
My possible solution to this is to rotate the video to apply what I need in different situations but I'm not having a working example with my code. Searching the internet I found solutions like this one here. The problem with this code is that is not compatible with the last version (It gives an compilation error) . I tried too to understand the logic of the library but I'm not having results. For example I experimented using the setMatrix instruction on the Movie object but It simply don't work.
public static void mergeVideo(int SegmentNumber) throws Exception {
Log.d("PM", "Merge process started");
Movie[] inMovies = new Movie[SegmentNumber] ;
//long[] Matrix = new long[SegmentNumber];
for (int i = 1 ; i <= SegmentNumber; i++){
File file = new File(getCompleteFilePath(i));
if (file.exists()){
FileInputStream fis = new FileInputStream(getCompleteFilePath(i));
//Set rotation I tried to experiment with this instruction but is not working
inMovies [i-1].setMatrix(Matrix.ROTATE_90);
inMovies [i-1] = MovieCreator.build(fis.getChannel());
Log.d("PM", "Video " + i + " merged" );
}
//fis.close();
}
List<Track> videoTracks = new LinkedList<Track>();
List<Track> audioTracks = new LinkedList<Track>();
for (Movie m : inMovies) {
for (Track t : m.getTracks()) {
if (t.getHandler().equals("soun")) {
audioTracks.add(t);
}
if (t.getHandler().equals("vide")) {
videoTracks.add(t);
}
}
}
Movie result = new Movie();
if (audioTracks.size() > 0) {
result.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
}
if (videoTracks.size() > 0) {
result.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
}
Container out = new DefaultMp4Builder().build(result);
//out.getMovieBox().getMovieHeaderBox().setMatrix(Matrix.ROTATE_180); //set orientation, default merged video have wrong orientation
// Create a media file name
//
String filename = getCompleteMergedVideoFilePath() ;
FileChannel fc = new RandomAccessFile(String.format(filename), "rw").getChannel();
out.writeContainer(fc);
fc.close();
//don't leave until the file is on his place
File file = new File (filename);
do {
if (! file.exists()){
Log.d("PM", "Result file not ready");
}
} while (! file.exists() );
//
Log.d("PM", "Merge process finished");
}
Have someone rotated video with the very last version of Mp4 parser? English is not my native language so I apologize any grammar error.
for (int i = 1; i <= SegmentNumber; i++) {
IsoFile isoFile = new IsoFile(getCompleteFilePath(i));
Movie m = new Movie();
List<TrackBox> trackBoxes = isoFile.getMovieBox().getBoxes(
TrackBox.class);
for (TrackBox trackBox : trackBoxes) {
trackBox.getTrackHeaderBox().setMatrix(Matrix.ROTATE_90);
m.addTrack(new Mp4TrackImpl(trackBox));
}
inMovies[i - 1] = m;
}
This is what I did to rotate a video.

Upload a file from Android to Drupal via Services Module

I tried to upload an image from Android Device to a Drupal Website
I used the Service module on Drupal side with method file.create.
The problem is that the files has been broken after the download.
The Files are smaller.
The filemime setting has n effect.
Javaside:
public Map saveFile(String localFilePath, String serverpath) throws XmlRpcException, IOException{
HashMap<String, Object> account = new HashMap<String, Object>();
File localFile = new File(localFilePath);
Log.w("XMLRPC", "FILENAME "+localFile.getName() + " original "+localFile.length());
String fileAsString = readFile(localFilePath);
// Sending side
byte[] data = fileAsString.getBytes("UTF-8");
byte[] base64 = Base64.encode(data,Base64.URL_SAFE);
account.put("file", base64);
account.put("filename", localFile.getName());
account.put("filepath", serverpath +"/"+ localFile.getName());
// account.put("filemime", "application/x-compressed");
account.put("filesize", Integer.parseInt(localFile.length()+""));//String.valueOf(localFile.length()));
Vector<Object> params = new Vector<Object>();
params.add(account);
return (Map) xmlRpcClient.execute(METHOD_FILE_CREATE, params);
}
Well, if you are not using a native android app for your Drupal site, you do not need any other 'interface' to upload the file! It should work as if you are uploading the file from desktop!

Youtube video not playing in InApp in android

In my application Youtube videos were playing perfectly in InApp. But certainly 2 days before I got the following alert message "Sorry, this video cannot be played" while playing the video and videos are not playing. I have tried different youtube video links, but no hope. If I use this code :
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/embed/Ai47z6qh8S0"));
startActivity(browserIntent);
Videos are playing then in browser. But I need this video to be played inside the application.
Previously I used the following code to create the youtube url
public static String calculateYouTubeUrl(String pYouTubeFmtQuality, boolean pFallback,
String pYouTubeVideoId) throws IOException,
ClientProtocolException, UnsupportedEncodingException {
String lUriStr = null;
HttpClient lClient = new DefaultHttpClient();
HttpGet lGetMethod = new HttpGet(OpenYouTubePlayerActivity.YOUTUBE_VIDEO_INFORMATION_URL +
pYouTubeVideoId);
HttpResponse lResp = null;
lResp = lClient.execute(lGetMethod);
ByteArrayOutputStream lBOS = new ByteArrayOutputStream();
String lInfoStr = null;
lResp.getEntity().writeTo(lBOS);
lInfoStr = new String(lBOS.toString("UTF-8"));
String[] lArgs=lInfoStr.split("&");
Map<String,String> lArgMap = new HashMap<String, String>();
for(int i=0; i<lArgs.length; i++){
String[] lArgValStrArr = lArgs[i].split("=");
if(lArgValStrArr != null){
if(lArgValStrArr.length >= 2){
lArgMap.put(lArgValStrArr[0], URLDecoder.decode(lArgValStrArr[1]));
}
}
}
//Find out the URI string from the parameters
//Populate the list of formats for the video
String lFmtList = URLDecoder.decode(lArgMap.get("fmt_list"));
ArrayList<Format> lFormats = new ArrayList<Format>();
if(null != lFmtList){
String lFormatStrs[] = lFmtList.split(",");
for(String lFormatStr : lFormatStrs){
Format lFormat = new Format(lFormatStr);
lFormats.add(lFormat);
}
}
//Populate the list of streams for the video
String lStreamList = lArgMap.get("url_encoded_fmt_stream_map");
if(null != lStreamList){
String lStreamStrs[] = lStreamList.split(",");
ArrayList<VideoStream> lStreams = new ArrayList<VideoStream>();
for(String lStreamStr : lStreamStrs){
VideoStream lStream = new VideoStream(lStreamStr);
lStreams.add(lStream);
}
//Search for the given format in the list of video formats
// if it is there, select the corresponding stream
// otherwise if fallback is requested, check for next lower format
int lFormatId = Integer.parseInt(pYouTubeFmtQuality);
Format lSearchFormat = new Format(lFormatId);
while(!lFormats.contains(lSearchFormat) && pFallback ){
int lOldId = lSearchFormat.getId();
int lNewId = getSupportedFallbackId(lOldId);
if(lOldId == lNewId){
break;
}
lSearchFormat = new Format(lNewId);
}
int lIndex = lFormats.indexOf(lSearchFormat);
if(lIndex >= 0){
VideoStream lSearchStream = lStreams.get(lIndex);
lUriStr = lSearchStream.getUrl();
}
}
//Return the URI string. It may be null if the format (or a fallback format if enabled)
// is not found in the list of formats for the video
return lUriStr;
}
Please help me to figure out this issue.
Thanks Santanu
This kind of youtube link wont work on android application, although it works fine on browsers. To make it work on an application you need to get the RTSP link of the video first.
Refer to this thread and see if you can find a solution there.
Example of youtube link working on android(I have tested this one):
rtsp://v2.cache6.c.youtube.com/CjgLENy73wIaLwn_aij76iwMRRMYESARFEIJbXYtZ29vZ2xlSARSB3JlbGF0ZWRgnfqw4Jajx8xPDA==/0/0/0/video.3gp
<iframe width="637" height="358" src="http://www.youtube.com/embed/Ai47z6qh8S0?fs=1&feature=oembed" frameborder="0" allowfullscreen=""></iframe>
try this or
you need to have hardware acceleration turned on
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("Video url"));
VideoActivity.this.startActivity(i);
//And add below code in Manifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

How can I get the View in the FileTransfer upload method in PhoneGap?

I have created a native android app with PhoneGap + Sencha Touch 2. I have succeeded in uploading a file to the server, however, I am having a problem accessing a View from the upload success callback function in the FileTransfer upload() method. Here is my code:
upload callback:
uploadPicture: function(imageURI) {
var options = new FileUploadOptions(),
params = new Object(),
fileTransfer = new FileTransfer(),
builder = this.getBuilder(),
app = this.getApplication(),
uri = encodeURI('/myservlet');
options.fileKey = 'file';
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = 'image/jpeg';
params.myparams = something;
params.moreparams = evenmore;
options.params = params;
options.chunkedMode = false;
fileTransfer.upload(imageURI, uri, this.uploadSuccess.bind(this), this.uploadError.bind(this), options);
},
upload success function
uploadSuccess: function (r) {
var builderChild = this.getBuilderChild(),
data = r.response.attachment;
builderChild.addInstance(builderChild.config, data);
navigator.notification.alert('Attachment successful.');
}
When I get into the uploadSuccess function my builderChild object is undefined. I have been able to use the builderChild object through this same Controller in other functions, but not in uploadSuccess.
Any ideas?
Give this a try, this is how I used to do it.
var ftSuccess = Ext.bind(this.uploadSuccess, this),
ftError = Ext.bind(this.uploadError, this);
fileTransfer.upload(imageURI, uri, ftSuccess, ftError, options);
Hope this helped

Categories

Resources