Good day everyone. Please am trying to play videos from a youtube channel. Let me break it down
1:On the first activity you get a list of users in a listview
2:When you click on the user,it loads their videos in another listview.
Everything is working perfectly to this point,But i don't know how to play the video,when that particular video is clicked. Here is my code.
package com.talagbe.videofeeds;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
public class YoutubeVideos extends Activity {
ListView listv;
YoutubeAdapter yadapter;
ArrayList<Youtube> y_list;
String url;
String Channel;
Context context=null;
ProgressDialog mprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.youtube);
y_list= new ArrayList<Youtube>();
listv = (ListView) findViewById(R.id.list2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
Channel = bundle.getString("Channel");
init();
}
public void init(){
Log.d("Chan",Channel);
AsyncHttpClient LoadVideos = new AsyncHttpClient();
LoadVideos.get("https://gdata.youtube.com/feeds/api/users/"+ Channel +"/uploads?v=2&alt=jsonc", new AsyncHttpResponseHandler(){
public void onSuccess(String data){
try {
JSONObject videoObj = new JSONObject(data);
//JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
JSONArray videosarray = videoObj.getJSONObject("data").getJSONArray("items");;
for(int i=0; i<videosarray.length();i++){
Youtube yvideos = new Youtube();
JSONObject video = videosarray.getJSONObject(i);
String videourl = video.getJSONObject("player").getString("mobile");
yvideos.setVideoTitle(video.getString("title"));
yvideos.setThumbs(video.getJSONObject("thumbnail").getString("sqDefault"));
//yvideos.setVideourl(videourl);
y_list.add(yvideos);
Log.d("Title",video.getString("title"));
Log.d("Video",videourl);
Log.d("Thumb",video.getJSONObject("thumbnail").getString("sqDefault"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
YoutubeAdapter Adapter = new YoutubeAdapter(getApplicationContext(),R.layout.videos,y_list);
listv.setAdapter(Adapter);
}
public void onStart(){
mprogress = ProgressDialog.show(YoutubeVideos.this, "Connecting...", "Retrieveing Videos");
}
public void onFinish(){
mprogress.dismiss();
}
public void onFailure(Throwable error, String content)
{
//Log.e("Error", content);
Toast.makeText(getBaseContext(), "Error Connecting to the internet", Toast.LENGTH_LONG).show();
}
});
}
}
You can make use of "YouTube Android Player API" provided by Google to play YouTube videos.
The YouTube Android Player API enables you to incorporate video
playback functionality into your Android applications. The API defines
methods for loading and playing YouTube videos (and playlists) and for
customizing and controlling the video playback experience.
Here's a sample app that utilizes YouTube Android Player API.
You can follow YouTube API
https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubeIntents
or you can direct intent default YouTube player by calling :
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + id));
startActivity(intent);
The id is the identifier after the questionmark in the url. For example: youtube.com/watch?v=ID
Another way is:
Intent videoIntent = new Intent(Intent.ACTION_VIEW);
videoIntent.setData(url);
videoIntent.setClassName("com.google.anddroid.youtube", "com.google.android.youtube.WatchActivity");
startActivity(videoIntent);
Related
I am building a cordova application which fetches JSON data from the server. One piece of information that I receive is the URL of 360 online images. I need to display those images in a photo sphere viewer (for Android). I' ve seen this API (needs cordova google play services plugin) and this library but I haven't managed to successfully use them inside the application.
Does anyone know a way of doing that? Can I open that type of image in a native intent?
Thanks in advance
Actually I managed to make it work. I am posting the solution, in case someone else finds it useful. Also created a plugin for that which can be found here
creating a simple plugin, I call from cordova the plugin class which downloads using AsyncTask an image from a URL and onPostExecute I call the Panorama activity that shows the viewer.
Intent intent = new Intent(cordova.getActivity().getApplicationContext(), PanoramaActivity.class);
intent.putExtra("filepath", file.getAbsolutePath());
cordova.getActivity().startActivity(intent);.
PanoramaActivity.java
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.panorama.Panorama;
import com.google.android.gms.panorama.PanoramaApi.PanoramaResult;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
import android.os.Environment;
public class PanoramaActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener{
File file;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mClient = new GoogleApiClient.Builder(this, this, this)
.addApi(Panorama.API)
.build();
Intent i= getIntent();
Bundle b = i.getExtras();
file = new File(b.getString("filepath"));
#Override
public void onStart() {
super.onStart();
mClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
Uri uri = Uri.fromFile(file);//Uri.parse(path);//Uri.fromFile(file);
Panorama.PanoramaApi.loadPanoramaInfo(mClient, uri).setResultCallback(
new ResultCallback<PanoramaResult>() {
#Override
public void onResult(PanoramaResult result) {
if (result.getStatus().isSuccess()) {
Intent viewerIntent = result.getViewerIntent();
Log.i(TAG, "found viewerIntent: " + viewerIntent);
if (viewerIntent != null) {
startActivity(viewerIntent);
}
} else {
Log.e(TAG, "error: " + result);
}
}
});
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "connection suspended: " + cause);
}
#Override
public void onConnectionFailed(ConnectionResult status) {
Log.e(TAG, "connection failed: " + status);
}
#Override
public void onStop() {
super.onStop();
mClient.disconnect();
Log.e(TAG, "ON Stop ");
}
On Android, I want to play TextToSpeech output through only one sound channel (think Shoulder Angel). To do this, I am currently using tts.synthesizeToFile(), and then playing back the dynamically-created file using the MediaPlayer. I use mediaPlayer.setVolume(0.0f, 1.0f) to play the audio through only one channel.
My working code is below.
My question is: is there a more direct way of playing TTS output through a single channel?
Using TextToSpeech to synthesize the file is time-consuming, and using MediaPlayer to play it back uses more resources than strictly necessary. I want this to be responsive and to work on low-end devices, so being kind to the CPU is important.
MainActivity.java
package com.example.pantts;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import android.os.Bundle;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private String toSpeak = "Hello, right ear!";
private static final String FILE_ID = "file";
private HashMap<String, String> hashMap = new HashMap<String, String>();
private String filename;
private TextToSpeech tts;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filename = getFilesDir() + "/" + "tts.wav";
Log.d("LOG", "file: " + filename);
// /data/data/com.example.pantts/files/tts.wav
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
tts = new TextToSpeech(this, this);
tts.setOnUtteranceProgressListener(mProgressListener);
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.UK);
hashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, FILE_ID);
// Using deprecated call for API 20 and earlier
tts.synthesizeToFile(toSpeak, hashMap, filename);
Log.d("LOG", "synthesizeToFile queued");
}
}
private UtteranceProgressListener mProgressListener =
new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d("LOG", "synthesizeToFile onStart " + utteranceId);
}
#Override
public void onError(String utteranceId) {
Log.d("LOG", "synthesizeToFile onError " + utteranceId);
}
#Override
public void onDone(String utteranceId) {
if (utteranceId.equals(FILE_ID)) { // Thanks to Hoan Nguyen for correcting this
Log.d("LOG", "synthesizeToFile onDone " + utteranceId);
try {
File ttsFile = new File(filename);
FileInputStream inputStream = new FileInputStream(ttsFile);
FileDescriptor fileDescriptor = inputStream.getFD();
mediaPlayer.reset();
mediaPlayer.setDataSource(fileDescriptor);
inputStream.close();
mediaPlayer.prepare();
mediaPlayer.setVolume(0.0f, 1.0f); // right channel only
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
There is nothing wrong with the synthesize, it is the comparison that is wrong. It should be
if (utteranceId.equals(FILE_ID))
i have for the passed 4 days tried to upload to youtube videos but i have failed please help me .
package com.example.testyoutube;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.mediarss.MediaCategory;
import com.google.gdata.data.media.mediarss.MediaDescription;
import com.google.gdata.data.media.mediarss.MediaKeywords;
import com.google.gdata.data.media.mediarss.MediaTitle;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YouTubeNamespace;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
public class MainActivity extends Activity {
private Button button;
private YouTubeService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitVideo("/storage/emulated/0/Pictures/Hello Camera/VID_20140523_204750.mp4",
"i have done it ", "Yooooooooo , it works", "fun");
}
});
}
public void submitVideo(String vName, String vTitle, String vDesc, String vCate) {
String developer_key = "api key"; // Registered developer key
String clientID = "gmailaccount"; // Server's Youtube account
String password = "passwordofgmailaccount"; // Server's Youtube password
service = new YouTubeService(clientID, developer_key); // YouTube Object, we take action by this.
try {
service.setUserCredentials(clientID,password);
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File videoFile = new File( vName ); // The video local file prepare to upload
String VIDEO_UPLOAD_FEED = "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
String mediaType = "video/*"; // Serach .flv MIME type may found more
String vKey1 = vCate; // Use same category and keyword
VideoEntry newEntry = new VideoEntry(); // YouTube video object type, they will return this after uploaded
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup(); // Collect all of the video information
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, vCate));
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent(vTitle);
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent(vDesc);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword(vKey1);
MediaFileSource ms = new MediaFileSource(videoFile, mediaType);
newEntry.setMediaSource(ms);
VideoEntry ve = null;
try {
ve = service.insert(new URL(VIDEO_UPLOAD_FEED), newEntry);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ve == null){
System.out.println("Submit to youtube fail.");
return ;
}
}
}
it says that this "service = new YouTubeService(clientID, developer_key);" has error but it does not explain why , please help (or suggest another code please)
U can ddo it using Intent
ContentValues content = new ContentValues(4);
content.put(Video.VideoColumns.DATE_ADDED,
System.currentTimeMillis() / 1000);
content.put(Video.Media.MIME_TYPE, "video/mp4");
content.put(MediaStore.Video.Media.DATA, "video_path");
ContentResolver resolver = getBaseContext().getContentResolver();
Uri uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, content);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Title");
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(sharingIntent,"share:"));
I have a camera application that can also record video. (Im developing on samsung S3)
I want to be able to open the gallery on the last recorded video.
I use this code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(file.getAbsolutePath()), "video/3gpp");
startActivity(intent);
The problem with that code is that the video immediately starts, and when it ends
the gallery activity close.
I want to be able to open the video without playing it, exactly like in my samsung S3.
thanks in advance!
To open particular image we can use this .. and its worked .
so please check with your requirement. Hope this will helps you..
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SDCARD123Activity extends Activity implements MediaScannerConnectionClient{
public String[] allFiles;
private String SCAN_PATH ;
private static final String FILE_TYPE="image/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File("/sdcard/Photo/");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for(int i=0;i<allFiles.length;i++)
{
Log.d("all file path"+i, allFiles[i]+allFiles.length);
}
// Uri uri= Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH=Environment.getExternalStorageDirectory().toString()+"/Photo/"+allFiles[0];
System.out.println(" SCAN_PATH " +SCAN_PATH);
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button)findViewById(R.id.scanBtn);
scanBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startScan();
}});
}
private void startScan()
{
Log.d("Connected","success"+conn);
if(conn!=null)
{
conn.disconnect();
}
conn = new MediaScannerConnection(this,this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected","success"+conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted",uri + "success"+conn);
System.out.println("URI " + uri);
if (uri != null)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally
{
conn.disconnect();
conn = null;
}
}
}
How can I download files using Android downloader? (The downloader that WebBrowser is using that too).
I tried something like this :
Intent i = new Intent(Intent.ACTION_VIEW , Uri.parse("MyUrl"));
startActivity(i);
Any better way?
Edit
I am using Android 2.2
Here you go.
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class DownloadManagerActivity extends Activity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("url for file to download"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
Don't forget to add android.permission.internet in manifest.
If you want to download it onto the user's SD card from an URL, you can just open it in the phone's default internet browser.
String url = "https://appharbor.com/assets/images/stackoverflow-logo.png";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
(Code from this question)
The android browser will then start and the file (in this case an image) will be downloaded.
You need to use HttpUrlConnection to do this on Android 2.2 and below. There is a very detailed tutorial on the internet that shows you how to do this (with a progress dialog box too).
Remember you must use an AsyncTask or a Thread to ensure that you do not block the UI thread during the actual download!
Yes, you cant perform network operation in the main thread. You can look up to this repository to download file.