I am running an application where i need to play an audio stored somewhere at a URL.
Before playing url i want to change the image of play button into pause.
I've hard time trying to do in the reference.
The UI is changed just after once it plays audio on URL and it takes 5-10 sec to play server URL. how can i change the image of the button before playing audio.
Can anybody please explain me why this is happening and what is the probable solution.
Please have a look over my code:-
((Button)v).setBackgroundResource(R.drawable.pause);
PlayPauseBtn.setId(1);
Toast.makeText(RadioActivity.this, "Loading...", Toast.LENGTH_LONG).show();
MediaController.mediaPlayStart(R.raw.acoustic_loop_bgm,
RadioActivity.this.getApplicationContext());
public static void mediaPlayStart(int resourcesId,final Context m_Context) {
try {
mp = new MediaPlayer();
mp.setDataSource(m_Context, Uri.parse(Contants.audioURL));
mp.prepare();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setLooping(true);
try {
mp.start();
} catch (Exception e) {
// TODO: handle exception
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("#####THE EXCEPTION IN THE MEDIA PLAYER PLAY==="+e.getMessage());
}
}
Here below is my logcat before playing sound.
06-21 17:15:17.661: W/KeyCharacterMap(1005): No keyboard for id 0
06-21 17:15:17.661: W/KeyCharacterMap(1005): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-21 17:15:21.910: I/System.out(1005): 00000000000000
06-21 17:15:21.910: I/System.out(1005): 2222222222
06-21 17:15:22.080: D/dalvikvm(1005): GC_FOR_MALLOC freed 3592 objects / 199296 bytes in 65ms
06-21 17:15:26.140: D/MediaPlayer(1005): Couldn't open file on client side, trying server side
It's maybe because you are using
mediaPlayer.prepare();
You better use the async method :
mediaPlayer.asyncPrepare();
This will not freeze your application and your icon will be changed immediatly.
EDIT :
mp.setDataSource(url);
mp.setOnPreparedListener(this);
mp.prepareAsync();
public void onPrepared(MediaPlayer player) {
mp.start();
}
Related
Hi we have an app in the playstore that has a module that play a stream from an url, the app works fine and we make a yearly release, but now that we are making changes, the part of the radio does not work, in any device.
Basically my code is
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource("http://radio.promosat.com:8104/");
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.prepareAsync();
}catch (Exception ex){
ex.printStackTrace();
}
I keep getting this error
E/MediaPlayer: Error (1,-2147483648)
This worked perfectly, the url that we use it's in the example code, it uses a pls file, that's where we obtained the stream url.
The error was the encoding of the stream...aacp is not supported in Android.
I'm getting the following back in Logcat starting MediaPlayer with a SPECIFIC URI. Normally every Uri, good or bad, will either play or come back with an error except this particular one.
I/MPS﹕ PrepAsync started
V/MediaPlayer﹕ message received msg=8, ext1=0, ext2=0
V/MediaPlayer﹕ unrecognized message: (8, 0, 0)
V/MediaPlayer﹕ callback application
V/MediaPlayer﹕ back from callback
... and hangs there.
I'm really just looking at how do I capture this conversation in an error handler but if someone knows the actual problem that's even better.
Source code FWIW:
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
}
try {
mediaPlayer.setDataSource(sUrl);
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.d(TAG, "Exception:"+e;
}
Also, I've tried creating an OnInfoListener, OnError and OnBufferingUpdateListener. These are never called. It's seems that mediaPlayer just goes away during onPrepareAsync.
Here is the URL if anyone is inspired to play with this.
http://54.196.206.122/entercom-koitfmaac-64
I just copy/pasted this into VLC to verify that the link is valid.
UPDATE: After looking at it more, if I wait long enough, eventually I get this:
I/dalvikvm﹕ threadid=3: reacting to signal 3
I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
UPDATE: This problem as was pointed out by Shubhang Malviya was that I needed to use URI.parse as:
mMediaPlayer.setDataSource(mContext, Uri.parse("http://54.196.206.122/entercom-koitfmaac-64"));
I thought It would be good If I share my implementation:
Try the following way of initialising your media player
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnInfoListener(this);
mMediaPlayer.setOnSeekCompleteListener(this);
mMediaPlayer.setDataSource(mContext, Uri.parse("http://54.196.206.122/entercom-koitfmaac-64"));
mMediaPlayer.prepareAsync();
} catch (IOException e) {
// reset media player
}
Mine onPrepared(MediaPlayer mp) is getting called after only a few seconds and it is playing your Music File.
Also FYI "Couldn't open file on client side, trying server side" is not an error message, but a debug message from the MediaPlayer. Logcat always says this when trying to play a network video stream.
There are 3 MediaPlayers and I want to set that these 3 sounds play seamlessly using setNextMediaPlayer(). The code is simple (repeated code is omitted)
mediaPlayer1 = new MediaPlayer();
try {
AssetFileDescriptor afd = getAssets().openFd("sound1.ogg");
mediaPlayer1.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer1.prepare();
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer1.start();
mediaPlayer2 = new MediaPlayer();
//Prepare 2nd player with sound2 without calling start()
mediaPlayer3 = new MediaPlayer();
//Prepare 3rd player with sound3 without calling start()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mediaPlayer1.setNextMediaPlayer(mediaPlayer2);
mediaPlayer2.setNextMediaPlayer(mediaPlayer3); //ERROR RUNTIME!!!
And here I get an error
E/MediaPlayer﹕ next player is not prepared
D/AndroidRuntime﹕ Shutting down VM
W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4175fda0)
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.testgaplesssound.app, PID: 28960
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.IllegalStateException at...
The error say MediaPlayer﹕ next player is not prepared so I tried setting onPrepared listener
mediaPlayer2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mediaPlayer2.setNextMediaPlayer(mediaPlayer3);
}
}
});
but onPrepared is never initiated!
So, how can I sent the 3rd player to play seamlessly as the first two?
I just tested the following setup with no errors, thinking your problem was with initialization. But then I noticed that you're starting your first player before initializing and chaining the other two. Reordering your code might solve your problem, but I'll post this as well, as it seems a simpler solution, to me, at least.
Move your audio files to the /res/raw folder, and initialize and start your players like so:
MediaPlayer mediaPlayer1, mediaPlayer2, mediaPlayer3;
mediaPlayer1 = MediaPlayer.create(this, R.raw.sound1);
mediaPlayer2 = MediaPlayer.create(this, R.raw.sound2);
mediaPlayer3 = MediaPlayer.create(this, R.raw.sound3);
mediaPlayer1.setNextMediaPlayer(mediaPlayer2);
mediaPlayer2.setNextMediaPlayer(mediaPlayer3);
mediaPlayer1.start();
NB: I tested under API 19, so you'll still need your version checks, if you're back-supporting.
I need to play sound from sd card. I have method that must do this but it's doesn't work.
When I use this method:
public class AudioPlayService extends Service
{
MediaPlayer mMediaPlayer;
..............
public void soundplay(String adr)
{
mMediaPlayer = new MediaPlayer();
try
{
if (mMediaPlayer.isPlaying())
{
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(adr);
mMediaPlayer.prepare();
} catch (IOException e)
{
}
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
mp = null;
}
});
}
Where String adr - it's absolute path to file on sd.
Then I call it:
AudioPlayService s = new AudioPlayService();
s.soundplay(iA.getSdDir() + "Files/Numbers/0.mp3");
and I get an err's:
12-09 13:04:13.829: E/MediaPlayer(16997): error (1, -2147483648)
12-09 13:04:13.829: E/MediaPlayer(16997): start called in state 0
12-09 13:04:13.829: E/MediaPlayer(16997): error (-38, 0)
12-09 13:04:13.839: E/MediaPlayer(16997): Error (-38,0)
I myself tried your code:
Mine worked fine when i put just "sdcard/1.mp3"
You ensure that the path is right or not
s.soundplay(iA.getSdDir() + "Files/Numbers/0.mp3");
Note:
If you are trying to make your method soundplay so as to stop previous audio and play the new audio file, then better would be not to perfom this inside that method
mMediaPlayer = new MediaPlayer();
Place this in constructor.
Otherwise each time you invoke s.soundplay(path) you will hear previous audio plus the new audio. ie,Previous one will not be stopped
player.start() put within try,catch block. Because if player not prepare your song ,still you are calling start method.start method is only called after playback is ready,
means prepare is success.Another thing is that you have to release the media player when your player is no longer.Otherwise there is so many player objects are running in back ground.
For some reason, your setDataSource() or Prepare() is failing. So after the exception, start()is giving the error, since the player is not in Prepared state. Add print statements in the catch block to know what is the exception. And move start() into the try catch block.
mMediaPlayer = new MediaPlayer();
try
{
if (mMediaPlayer.isPlaying())
{
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(adr);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e)
{
e.printStackTrace();
}
I have a list of songs that I'm streaming using the MediaPlayer. Some of the songs consistently work and others consistently do not work. I can't see a difference between these files, and they seem to play fine in itunes and such.
When the songs fail it is throwing an IllegalStateException on the mediaPlayer.prepare() line. The IllegalStateException that is thrown has no useful info in it, (detailMessage is null, stackState is null)
Here is my code
try {
mediaPlayer.setDataSource(media.url);
setPlayerState(PlayerState.PREPARING);
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "bad stream");
}
Here is a url to the file that does NOT work:
skdy.bryceb.dev.mediarain.com/song.m4a
Here is one that DOES work:
skdy.bryceb.dev.mediarain.com/song2.m4a
Any ideas why this works on some songs and fails on others?
Thanks MisterSquonk I'm sure that way would work.
In my particular case after beating my head against the wall for a while I realized that on some songs, I was getting to the buffered amount before the player state was getting set to prepared. So I added a check to make sure that the MediaPlayer was in the "PREPARED" state and then it worked great:
// Media prepared listener
mediaPlayer.setOnPreparedListener(
new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
setPlayerState(PlayerState.PREPARED);
}
});
// Media buffer listener
mediaPlayer.setOnBufferingUpdateListener(
new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// Sometimes the song will finish playing before the 100% loaded in has been
// dispatched, which result in the song playing again, so check to see if the
// song has completed first
if(getPlayerState() == PlayerState.COMPLETED)
return;
if(getPlayerState() == PlayerState.PAUSED)
return;
// If the music isn't already playing, and the buffer has been reached
if(!mediaPlayer.isPlaying() && percent > PERCENT_BUFFER) {
if(getPlayerState() == PlayerState.PREPARED)
{
mediaPlayer.start();
setPlayerState(PlayerState.PLAYING);
}
//if it isn't prepared, then we'll wait till the next buffering
//update
return;
}
}
});
OK, I hacked together a minimal Mediaplayer implementation in a 'sandbox' app/activity I always keep spare for testing.
I might be wrong but if you're streaming these songs over the net, you'll need to prefix the url with http://.
I tried the urls with Winamp and Chrome verbatim (no protocol prefix string) and they worked fine although it's likely both of those applications will use some form of intelligence to work out how to connect/stream.
If I tried that in my mediaPlayer code, I get the same exception as you but if I prefix the urls with http:// the songs play fine.
Example...
// Activity scope
Button button;
CheckBox checkBox;
String url = "";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button declared in my activity
button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
if (!checkBox.isChecked())
url = getString(R.string.url_song1);
else
url = getString(R.string.url_song2);
mediaPlayer = new MediaPlayer();
}
#Override
public void onClick(View arg0) {
try {
Log.i(TAG, "onClick() entered...");
mediaPlayer.setDataSource(url);
Log.i(TAG, "Preparing mediaplayer...");
mediaPlayer.prepare();
Log.i(TAG, "Starting mediaplayer...");
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "bad stream");
}
}
If I copy the songs to my SD card both play fine and as long as the internet url strings have an 'http://' prefix then they also work.