I'm trying to add media controls to my app but I can't get the RemoteMediaPlayer to send commands.
The video starts playing but then I can't control it.
This is the code I use:
RemoteMediaPlayer mRemoteMediaPlayer = new RemoteMediaPlayer();
try {
Cast.CastApi.setMessageReceivedCallbacks(apiClient, mRemoteMediaPlayer.getNamespace(), mRemoteMediaPlayer);
MediaMetadata mediaMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
JSONObject jsonExtra = new JSONObject();
mediaMetadata.putString(MediaMetadata.KEY_TITLE, "My video");
if (mediaType != null) {
jsonExtra.put("type", mediaType);
}
if ("audio".equals(mediaType)) {
mimeType = "audio/mp3";
}
com.google.android.gms.cast.MediaInfo.Builder builder = new MediaInfo.Builder(getUrl()).setContentType(mimeType).setMetadata(mediaMetadata).setCustomData(jsonExtra);
builder.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED);
MediaInfo mediaInfo = builder.build();
mRemoteMediaPlayer.load(apiClient, mediaInfo, true, inititalTime).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(MediaChannelResult result) {
if (result.getStatus().isSuccess()) {
log(context, "Media loaded successfully");
}
}
});
Thread.sleep(5000);
mRemoteMediaPlayer.pause(apiClient);
} catch (IllegalStateException e) {
log(context, "Problem occurred with media during loading " + e);
} catch (IOException e) {
log(context, "Problem occurred with media during loading " + e);
} catch (JSONException e) {
log(context, "Problem occurred with media during loading " + e);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You may notice that at the end I wait 5 seconds to make sure that the video is playing and then try to pause it.
This always results in an IllegalStateException with the message:
No current media session
Am I missing something?
I also notice that the ResultCallback is never called after the video starts playing. Maybe this is also related to the same issue I'm experiencing.
Thanks in advance.
It is not clear when you are running this piece of code. Do not set a sleep like you did; you have to register callbacks on mRemoteMediaPlayer to be notified when status or metadata changes on the remote player. When the status changed listener is called, get the updated status by calling mRemoteMediaPlayer.getMediaStatus().getPlayerState() and based on the status (whether it is playing, buffering, idle, paused), make the appropriate decision. In asynchronous systems, never use "sleep()", always hook into the callbacks.
Related
I have the following running at startup inside of an IntentService
threadManager.postBackgroundRunnableDelayed(() -> {
try {
// Calling getToken and getId must be on separate thread. Otherwise, it blocks UI thread.
String token = instanceID.getToken(SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
String id = instanceID.getId();
Timber.d("id: " + id);
Timber.d("token: " + token);
lazyRestQueue.get().sendGcmToken(new GcmPushRequest(id, token), getSendGcmTokenCallback());
setupAnalytics(token);
} catch (IOException e) {
Timber.e(e, "Exception during registration");
Crashlytics.logException(e);
setHasToken(false);
} catch (RuntimeException e) {
// This will be thrown if Localytics was not properly setup
Timber.e(e, "Exception during registration");
}
});
When I run it on anything below API 18 it causes the app to close (not crash oddly, just close)
can someone give me advice on this? I know it probably has to do with the service or something not timing properly
I am working on streaming radio application. everything is working fine except the changing the equalizer effect does not affect sound.
Changing the equalizer effect by calling usePreset(preset) does not make any changes in the sound effects.
Even though there is no error, why usePreset does not change the sound effects.
I have tested in samsung galaxy sII with 4.0.3.
public void startPlayer() {
//
// Check whether we can acquire the audio focus
// to start the player
//
if (!requestAudioFocus()) {
return;
}
if (null != mAudioPlayer) {
if (mAudioPlayer.isPlaying()) {
mAudioPlayer.stop();
}
mAudioPlayer.reset();
} else {
mAudioPlayer = new MediaPlayer();
mAudioPlayer.reset();
}
try {
notifyProgressUpdate(PLAYER_INITIALIZING);
try {
mEqualizer = new Equalizer(0, mAudioPlayer.getAudioSessionId());
mEqualizer.setEnabled(true);
Log.d(TAG,
"Audio Session ID " + mAudioPlayer.getAudioSessionId()
+ "Equalizer " + mEqualizer + " Preset "
+ mEqualizer.getCurrentPreset());
} catch (Exception ex) {
mEqualizer = null;
}
mAudioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mAudioPlayer.setDataSource(mCurrentTrack.getStreamURL());
//
// Add the Listener to track the player status
//
mAudioPlayer.setOnCompletionListener(this);
mAudioPlayer.setOnBufferingUpdateListener(this);
mAudioPlayer.setOnPreparedListener(this);
mAudioPlayer.setOnInfoListener(this);
mAudioPlayer.setOnErrorListener(this);
notifyProgressUpdate(PLAYER_BUFFERING);
mAudioPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//Get the available presets from the equalizer
public String[] getEqualizerPresets() {
String[] presets = null;
short noOfPresets = -1;
if (null != mEqualizer) {
noOfPresets = mEqualizer.getNumberOfPresets();
presets = new String[noOfPresets];
for (short index = 0; index < noOfPresets; index++) {
presets[index] = mEqualizer.getPresetName(index);
}
}
return presets;
}
//Set the user preferred presets
public void setEqualizerPreset(int position) {
if (null != mEqualizer) {
Log.d(TAG, "setting equlizer effects " + position);
Log.d(TAG, "Equalizer " + mEqualizer + " set Preset " + position);
mEqualizer.usePreset((short)position);
Log.d(TAG, "Equalizer " + mEqualizer + " current Preset "
+ mEqualizer.getCurrentPreset());
}
}
Appreciate your help to identify the issue.
EDIT
This issue is not resolved yet. i did not find any sample code which explain Equalizer Preset usage.
Any reference to code sample which uses Preset welcome.
this is a fully source code for equalizer, hope this will help you
I have the same problem. When I load it on emulator it produce an error that I don't really know why, it always says ...audiofx.Equalizer. and audiofx.AudioEffect. or something similar. But I have discovered that if you have other media player like n7player in my case, try to close it and try again your media player. In my case it works, but I think that it has to be one method to get some equalizer that is active.
Why doesn't the MediaPlayer show the video as soon as it is available. What I mean is on the IPhone when a video is played the video shows up right away. Even when returning from pause. But on the Android the screen stays black for a couple of milliseconds to a second depending on the device used and how many processes are running in the background.
I'm asking this because i want to use one of the beginning frames from my video play as a type of screenshot and currently I'm using a handler to wait 1 second before pausing the video.
Can someone tell me a quick way to make the video show up as soon as it is started or even prepared instead of my workaround?
EDIT:
Here is how I prepare my video player so It should be prepared right.
private void initVideo()
{
Log.i("VideoPlayer", "Initialize Video File" + videoFileName);
AssetFileDescriptor afd;
try {
if(videoFileName != null);
{
afd = getAssets().openFd(videoFileName);
vidplayer = new MediaPlayer();
vidplayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
vidplayer.setDisplay(holder);
vidplayer.prepare();
vidplayer.setOnCompletionListener(this);
vidplayer.setOnPreparedListener(this);
//Log.i("INITVIDEO", Integer.toString(videoPausedAt));
vidplayer.seekTo(videoPausedAt);
//Log.i("VideoPlayer", "video Prepared");
videoDuration = vidplayer.getDuration()/1000;
isVideoReady = true;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e)
{
//Log.i("InitPlayer", e.getClass().toString());
e.printStackTrace();
}
}
For the background, you can get a thumbnail of the video:
private Bitmap getThumbnail(String path){
try{
return ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
}catch(Exception e){
return null;
}
}
When the video starts, you'll need to set the background back to null or you won't be able to see the video.
As for it not playing right away, it should play as soon as start() is called if you prepared it correctly, but it could be delayed if it has to load data let's say from a stream over the internet.
I have found that it is the phones fault.(mostly) Video's will show up automatically unless phone is bogged down with apps and thus loading of the video takes longer (noticed after having a voip service running).
I have online radio (shout cast ) in web. I want to develop android app for listen this stream. so I want to know how to play online stream in android. using URL. In Android Im not going to Stream the audio. I want listen the web stream from android app.
How to do that..?
thanks
Something like
private void init() throws IOException {
try {
mediaPlayer = new MediaPlayer();
String streamPath = "";//enter path
mediaPlayer.setDataSource(streamPath);
mediaPlayer.prepare();
} catch (MalformedURLException ex) {
throw new RuntimeException("Wrong url for mediaplayer! " + ex);
} catch (IllegalStateException ex) {
} catch (IllegalArgumentException ex) {
throw new RuntimeException("Wrong url for mediaplayer! " + ex);
}
}
private void play() {
mediaPlayer.start();
}
Please refer the link it may help you a while, http://developer.android.com/guide/topics/media/index.html
I'm currently developing an Android application that plays a sound to the user at various intervals. I have working code (included below) which functions exactly as expected on my Hero (running 2.2) and on the 1.6 emulator. However, it doesn't work on my friends Xperia x8 -- no sound is played. He has a notification tone set, which plays fine when he receives a text and so on.
private void prepareAudio(){
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mp = new MediaPlayer();
if(alert != null){
try {
mp.setDataSource(ctx, alert);
} catch (IllegalArgumentException e) {
Log.i("Prepare Audio", e.getMessage());
} catch (SecurityException e) {
Log.i("Prepare Audio", e.getMessage());
} catch (IllegalStateException e) {
Log.i("Prepare Audio", e.getMessage());
} catch (IOException e) {
Log.i("Prepare Audio", e.getMessage());
}
}
am = (AudioManager)ctx.getSystemService(Context.AUDIO_SERVICE);
}
private void notifyUser(){
if(alert != null){
if (am.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setLooping(false);
try {
mp.prepare();
} catch (IllegalStateException e) {
Log.i("Notify User", e.getMessage());
} catch (IOException e) {
Log.i("Notify User", e.getMessage());
}
mp.start();
} else {
Log.i("Notify User", "Alarm volume zero");
}
} else {
Log.i("Notify User", "Uri is null");
}
long[] pattern = {0,200,300,600};
v.vibrate(pattern, -1);
}
PrepareAudio is called on initialising the class, and notifyUser every time we want to play the sound. The phone always vibrates when it should, so notifyUser is definitely being called.
The version my friend has installed uses e.printStackTrace rather than Log.i, so there's nothing being spat out in logcat. I'm going to try and get hold of his phone to update it to a version with Log.i, but in the meantime is there anything obviously wrong with the code that could cause such an intermittent problem?
Thanks,
So it turned out that updating my exception handling as listed in the original post appears to have fixed the problem.
If you're using the above code for anything, it's worth noting that sometimes e.getMessage() returns null, so rather than
Log.i("Notify User", e.getMessage());
use
Log.i("Notify User", e.getMessage() + "");
To avoid any nasty FCs when an exception is thrown.
Sorry for the incidentally unanswerable question!
Not sure, but older versions of Android had problems playing WAV files. Are these WAV files or MP3 files that you're trying to play?