Android MediaPlayer not playing sound on some platforms - android

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?

Related

Chromecast Android SDK: RemoteMediaPlayer always ends in IllegalStateException when trying to control

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.

Set Bitrate for the stream audio in android

I have a simple android app, thar stream online radio, everything is OK, but the client want the app has 2 options, 128 kbp/s and 38 kbp/s. how I can set bitrate to the MediaPlayer Class in asdroid?
this is my pla action:
public void actionPlay(View view) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you refer to the documentation using prepareAsync() is better from streams. If you use prepare(), you will block it until enough data is buffered.
mediaPlayer.prepareAsync();
Refer here.
As for setting the bit rate there is no mention of it in the official documentation.
Perhaps you need to go NDK to realize it and that will require lots of work..

Media Player Show video

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).

MediaPlayer doesnt work after upgrade to Gingerbread 2.3.4

I have an app that will play a tone, it did work perfectly until I installed it on Gingerbread 2.3.4 based android phone. The problem is I don't see any exception thrown, and no sound is generated, exactly same code does play sound in pre gingerbread phone. Here is the code that plays the sound.
MediaPlayer mp = new MediaPlayer();
//mp.release();
try {
String audioFilePath = "content://media/internal/audio/media/20";
mp.setDataSource(audioFilePath);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have comments placed before and after the code to play sound, all comments are printed as if sound is played, but there is no sound.
Thanks for any help.
never mind, seems like somehow the volume on alerts was set to 0, I actually went to actual folder, selected a file, played it manually and then turned the volume up while being played and all was well afterwards.

How to play online stream in Android

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

Categories

Resources