How to get streaming bitrate with MediaPlayer? - java

I'm developing a stream video app in Android with MediaPlayer. The problem is that I need to show the current bitrate, but I haven't found any valid suggestions on how to do get it?
Here is how I'm setting the video url to play:
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(VIDEO_PATH);
mediaPlayer.prepare();
mediaPlayer.init();
} catch (IOException e) {
e.printStackTrace();
}
I don't know if the only way to get that working is using ExoPlayer (which I've read it may be possible)
Any suggestions?
Thanks!

Apparently you cannot do this with MediaPlayer but you can use MediaMetadataRetriever, which is available since API level 10, i.e., quite a while ago.
int getBitRate(String url) {
final MediaMetadataRetriever mmr = new MediaMetadataRetriever();
try {
mmr.setDataSource(url, Collections.EMPTY_MAP);
return Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
} catch (NumberFormatException e) {
return 0;
} finally {
mmr.release();
}
}
The disadvantage this can have is that you will make an extra HTTP request for getting the metadata (only an RTT if you are streaming from an URI; if you are reading from an file descriptor it could be more serious). Hopefully no big deal.

Related

Play Video From URL By Using Vuforia for Android Native?

I want to play a video from URL by using the Vuforia Android Native API.
I have changed the code in the VideoPlayback sample, as shown below:
VideoPlayback.java
Video from Url
mMovieName[STONES] = "..Youtube Video link..";
mMovieName[CHIPS] = "..Youtube Video link..";
mMovieName[celebVM_LOGO] = "..Youtube Video link..";
I removed some code from VideoPlayerHelper.java as shown below:
for Video from Url, in Load method
AssetFileDescriptor afd = mParentActivity.getAssets().openFd(filename);
mMediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
Added:
mMediaPlayer.setDataSource(filename);
And removing the code
try {
AssetFileDescriptor afd = mParentActivity.getAssets().openFd(filename);
afd.close();
} catch (Exception e) {
Log.d(LOGTAG, "File does not exist");
mCurrentState = MEDIA_STATE.ERROR;
mMediaPlayerLock.unlock();
mSurfaceTextureLock.unlock();
return false;
}
It's not working, can anybody suggest why? Please refer to this link for more information:
https://developer.vuforia.com/forum/android/how-work-video-url-videoplayback
I believe it will only work with links to the actual videos, for example this one.
mMediaPlayer.setDataSource("../video.mp4"); //or any video type

Android Mp3 live streaming from url

Hello everyone,
I'm trying to play mp3 audio from a url (radio) using media player class. It is running but it took too much time to start. I know this question is already asked on this site. But I need help. If their is no solution for that kindly tell me alternative method . Reference code or tutorial would be a great help.here is my java code.
public void streaming(String url)
{
MediaPlayer mediaPlayer = new MediaPlayer();
try {
Log.i("stream", "connecting data source");
mediaPlayer.setDataSource(url);
Log.i("stream", "preparing");
mediaPlayer.prepare();
Log.i("stream", "prepared");
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
catch(Exception e){
e.printStackTrace();
}
mediaPlayer.start();
Log.i("stream", "Started");
}
}

Google Drive for Android SDK Doesn't List Files

I've got a really odd problem with the Google Drive Android SDK. I've been using it for several months now, and until last week it performed perfectly. However, there is now a really odd error, which doesn't occur all the time but does 9 out of 10 times.
I'm trying to list the user's files and folders stored in a particular Google Drive folder. When I'm trying to use the method Drive.files().list().execute(), 9 out of 10 times literally nothing happens. The method just hangs, and even if I leave it for an hour, it just remains doing... nothing.
The code I'm using is below - all of this being run within the doInBackground of an AsyncTask. I've checked credentials - they are all fine, as is the app's certificate's SHA1 hash. No exceptions are thrown. Google searches have yielded nothing. Here is the particular bit of code that's bothering me:
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
SettingsActivity.this, Arrays.asList(DriveScopes.DRIVE));
if (googleAccountName != null && googleAccountName.length() > 0) {
credential.setSelectedAccountName(googleAccountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
service.files().list().execute(); // Google Drive fails here
} else {
// ...
}
} catch (final UserRecoverableAuthIOException e) {
// Authorisation Needed
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
startActivityForResult(e.getIntent(), REQUEST_AUTHORISE_GDRIVE);
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account due to Exception after trying to show the Google Drive authroise request intent, as the UserRecoverableIOException was originally thrown. Error message:\n" + e.getMessage());
}
}
});
Log.d("SettingsActivity: Google Drive", "UserRecoverableAuthIOException when trying to add Google Drive account. This is normal if this is the first time the user has tried to use Google Drive. Error message:\n" + e.getMessage());
return;
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account. Error message:\n" + e.getMessage());
return;
}
I'm using Drive API v2. Thanks everyone!
Edit
Having played around a bit more, it turns out this isn't for just listing files. Trying to interact with any file on Google Drive behaves the same way - deleting, downloading, creating... Anything! I have also noticed that putting the device in aeroplane mode so it has not internet access makes no difference either: Google Drive doesn't throw an exception, or even return, it just freezes the thread it's on.
I've updated to the very latest Drive API lib but that hasn't helped. I remembered that the error happened soon after I added the JSch SSH library to the project, so I removed that, but it made no difference. Removing and re-adding the Drive API v2 has made no difference either, and nor has cleaning the project.
Edit 2
I've found something which may be significant. On the Google Developer console, I had some Drive errors recorded as follows:
TOP ERRORS:
Requests % Requests Methods Error codes
18 38.30% drive.files.list 400
14 29.79% drive.files.insert 500
11 23.40% drive.files.update 500
4 8.51% drive.files.get 400
Do you reckon these are the errors? How could I fix them? Thanks
This is my code and it's work
new AsyncTask<Void, Void, List<File>>() {
#Override
protected List<File> doInBackground(Void... params) {
List<File> result = new ArrayList<File>();
try {
com.google.api.services.drive.Drive.Files.List list = service.files().list();
list.setQ("'" + sourcePath + "' in parents");
FileList fileList = list.execute();
result = fileList.getItems();
if(result != null) {
return result;
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(List<File> result) {
//This is List file from Google Drive
};
}.execute();
I've come up with a solution which does work, and thought I'd post it so others could see it if they happen to come across the problem.
Luckily, I had backed up all of the previous versions of the app. So I restored the whole project to how it was two weeks ago, copied and pasted all changes from the newer version which had been made since then, and it worked. I don't see why this should work, since the end result is the same project, but it does!
Google Drive List Files
This might help you.. Try to display it in ListView u will see all fetched folders
public void if_db_updated(Drive service)
{
try {
Files.List request = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'");
FileList files = request.execute();
for(File file : files.getItems())
{
String title = file.getTitle();
showToast(title);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});

Saving a .jpg to byte[] android

This shouldn't be that hard, but I cannot figure this out. I need to save an image, on my end only, and build it dynamically so all my users will view these images. The tutorials on Parse.com are very helpful, but not in the case of images. I need detailed explanations or helpful links. Thanks for looking.
This is all I have so far as far as saving an image. I am properly getting the file in my Data Browser, but if I try to view it, it only shows my string "beatdown.jpg" not the actual jpg.
....
private void saveImage() {
// TODO Auto-generated method stub
InputStream header = new FileInputStream("beatdown.jpg");
byte[] head = IOUtils.toByteArray(header);
ParseFile file = new ParseFile(head);
try{
file.save();
} catch (ParseException e) {
e.printStackTrace();
}
ParseObject displayImage = new ParseObject("displayImage");
displayImage.put("header", file);
try{
displayImage.save();
} catch (ParseException e1){
e1.printStackTrace();
}
}
I understand I am trying to get the string of "beatdown.jpg" to bytes in the code above, and it is not handling it as a .jpg. But I don't know how to make it a .jpg.
EDIT: I added commons-io. But when I run the code (see the above updated code), it won't register on anything on parse.com. I am getting this in my logcat;
Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection#40cf2498 that was originally bound here
The key elements are:
File f = new File("pathToFile");
FileInputStream fis = new FileInputStream(f);
byte[] bytes = new byte[f.length()];
fis.read(bytes);
Of course there's exception handling and the like to do, but this should be enough to give you the general idea.

How to play a WAV in Java, when the WAV is contained inside the JAR

I've been trying to deal with sound on my Applet for a bit now, and Instead of trying all the different methods, what is the best way to play Sound in Java? There are a few requirements:
Needs to be able to loop
Needs to be able to load a WAV from an archive JAR(I think with the getClass().getResource)
Needs to be able to play more than one sound at the same time, and not clip already playing sounds
Thanks you so much for looking at my question and I hope you guys have an answer!
Thanks to the wonderful help I almost have it working with this:
public class MyGame() {
Clip bullet;
public void init(){
try {
bullet = AudioSystem.getClip();
URL url2 = this.getClass().getResource("bulletSound.wav");
AudioInputStream ais2 = AudioSystem.getAudioInputStream( url2 );
bullet.open(ais2);
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
randomMethodToPlayBullet(){
bullet.setFramePosition(0);
bullet.start();
}
}
The problem is that the bullet sound plays, but if the randomMethodToPlayBullet is called say twice in a row, before the first bullet sound is done, the seonc one doesnt play.
The best way to load resources from jar file is to put in the same folder a class and get the resource with .class.getResource(...) or .class.getResourceaAsStream(...) methods:
URL url = ClazzInTheFolderOfMyMidiFile.class.getResource(nameOfMidiFile);
or
InputStream resourceAsStream = ClazzInTheFolderOfMyMidiFile.class.getResourceAsStream(nameOfMidiFile);
The answer for:
Small samples is Clip. See the Java Sound info. page for an example of use.
Large samples is BigClip.
You can't play the same Clip twice at the same time. You have to create another instance of Clip to play the sound twice at the same time.
Note that there will be a limit how many clips you can play, so the clip API may not be suited to support a sound-heavy game.

Categories