android mediaplayer start called in state1 - android

I am trying to play an audio file when the app started, but I am getting an error says that start called in state 1 Error (-38,0), here is my code:
public void audioPlayer(){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.create(this, R.raw.music);
onPrepared(mp);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onPrepared(MediaPlayer mp) {
mp.start();
}

public void audioPlayer(){
MediaPlayer mp = new MediaPlayer();
mp.setOnPreparedListener(mListener);
try {
mp.setDataSource(this, R.raw.music);
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
private OnPreparedListener mListener=new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
};

Related

Play audio from url one after other

I want to play/stream audio from url one after other automatically.
here what I have tried:
final String audioUrl[] = {"https://www.googleapis.com/storage/v1/b/ezconnectpoc/o/NV.wav?alt=media", "https://www.googleapis.com/storage/v1/b/ezconnectpoc/o/cqo.wav?alt=media"};
backtobackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(audioUrl[currentTrack]);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
Log.d("Current track",currentTrack+"");
Log.d("audioUrl.length",audioUrl.length+"");
if (currentTrack < audioUrl.length) {
currentTrack++;
mediaPlayer.setDataSource(audioUrl[currentTrack]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
mediaPlayer.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
// make something
}
}
});
My first audio url gets played when I click on backtoback named button but failed to play second audio from url.
changed this part of code
mediaPlayer.reset();
mediaPlayer.setDataSource(audioUrl[currentTrack]);
mediaPlayer.prepareAsync();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
currentTrack++;
and worked.

android Media player not reading some mp3 url

i've created a playlist based on Media Player class. The thing is that it succeed in reading some mp3 url and it doesn't for another ones.
For example here is a directory of mp3 i've uploaded but no one is working:
http://rajaapp12.0fees.us/gbv3/
in the other hands an mp3 which work:
http://mp3.mp3zik.com/music/Music-Rap/Casa%20Verde%202009/track%20(14).mp3
I don't think there is a problem with the code since it works already witch some url, but here is the most iportant part of it :
public void beginLrcPlay(){
killMediaPlayer();
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(songEnCours.getSource_128());
mPlayer.setLooping(true);
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
if (mTimer == null) {
mTimer = new Timer();
mTask = new LrcTask();
mTimer.scheduleAtFixedRate(mTask, 0, mPalyTimerDuration);
}
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//fin musique ajouter action !
stopLrcPlay();
chantSuivant();
btnPlay.setImageResource(R.drawable.bg_selector_btn_play);
}
});
mPlayer.setOnBufferingUpdateListener(onBufferingUpdateListener);
mPlayer.prepare();
mPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

adding mutiple audio file in android

i'm adding multiple audio files using
try {
MediaPlayer mp = MediaPlayer.create(context, R.raw.play);
audioArr[0] = mp;
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
and releasing media in a function as
for (MediaPlayer media : audioList) {
if (media != null) {
if(media.isPlaying())
media.stop();
media.release();
media = null;
}
}
stil i'm not able to play multiple audio file in my application,first time playing with audio,so kindly guide
Try this :
void addSongs()
{
File songs = new File(sdPath); //sdPath is the path of your audio files
if(songs.listFiles(new SongFilter()).length > 0)
{
for(File file : songs.listFiles(new SongFilter()))
{
vector.add(file.getName());
}
arrayAdapter.setNotifyOnChange(true); //arrayAdapter Array Adapter
songList.setAdapter(arrayAdapter); //songList is a ListView
}
}
SongFilter Class like this :
class SongFilter implements FilenameFilter
{
public boolean accept(File dir, String filename)
{
return (filename.endsWith(".mp3"));
}
}
buttonSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// play another sound here.do your stuff whatever you want to do
mp.stop();
}
});
public class AudioActivity extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {##}
private void start(){
songs= new int[] {R.raw.s1,R.raw.s2,R.raw.s3,R.raw.s4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
**// This is the completion listener registered with mediaplayer instance.**
playNextSong();
}
private void playNextSong()
{
current_index = (current_index +1)% songs.length;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
if(current_index!=0){
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e){}
catch (IllegalStateException e){}
catch (IOException e){}
}else{
mediaPlayer.stop();
}
}
}

Trigger an event when mediaPlayer stops

I am making an app that uses sound effects. I would like to know how i can detect when a sound has finished playing and trigger an event .
i tried this :
player = new MediaPlayer();
if (player != null) {
player.reset();
player.release();
}
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
sonar.setBackgroundResource(R.drawable.sonar_off);
stopPlay();
}
});
if(state==1){
player = MediaPlayer.create(this, R.raw.sonar_slow);
}else if(state==2){
player = MediaPlayer.create(this, R.raw.sonar_medium);
}else if(state==3){
player = MediaPlayer.create(this, R.raw.sonar_fast);
}
try{
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
You can set an OnCompleteListener() to the player object. The code for it is:
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
"your code comes here"
}
});
Here the mPlayer is the object of the MediaPlayer which is currently running.
There are multiple ways to play sounds, assuming you use the MediaPlayer class you could register a MediaPlayer.OnCompletionListener

Media Player called in state 0, error (-38,0)

I am currently trying to design a simple app that streams an internet radio station. I have the URL for the station and am setting up the Media Player like
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
The program isn't crashing when emulated, but nothing is playing and I am get the following error:
start called in state 0
and right below it is
Error (-38,0)
Does anyone know what this means?
I've read a little about these state errors, but couldn't find anything that applies to my project.
You need to call mediaPlayer.start() in the onPrepared method by using a listener.
You are getting this error because you are calling mediaPlayer.start() before it has reached the prepared state.
Here is how you can do it :
mp.setDataSource(url);
mp.setOnPreparedListener(this);
mp.prepareAsync();
public void onPrepared(MediaPlayer player) {
player.start();
}
It seems like Error -38 means a state-exception (as the error-message indicates). For example if you call start(), before the song was ready, or when you call pause(), even if the song isn't playing at all.
To fix this issue check the state of the mediaPlayer before calling the methods. For example:
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
Additionally, the MediaPlayer is sending event-messages. Even if you do not need the prepared-event (although it would be a good idea to not start the playback before this event was fired) you must set a callback-listener. This also holds true for the OnErrorListener, OnCompletionListener, OnPreparedListener and OnSeekCompletedListener (if you call the seek method).
Listeners can be attached simply by
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// Do something. For example: playButton.setEnabled(true);
}
});
I got this error when I was trying to get the current position (MediaPlayer.getCurrentPosition()) of media player when it wasn't in the prepared stated. I got around this by Keeping track of its state and only calling the getCurrentPosition() method after onPreparedListener is called.
This is my code,tested and working fine:
package com.example.com.mak.mediaplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mpp = MediaPlayer.create(this, R.raw.red); //mp3 file in res/raw folder
Button btnplay = (Button) findViewById(R.id.btnplay); //Play
btnplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vone) {
mpp.start();
}
});
Button btnpause = (Button) findViewById(R.id.btnpause); //Pause
btnpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vtwo) {
if (mpp.isPlaying()) {
mpp.pause();
mpp.seekTo(0);
}
}
});
}
}
I encountered the same issue few days ago. My audio MediaPlayer works fine on devices with high processing power, but for slow devices, the media player just did not play some time and from LogCat it had many complain about called in wrong state. So I resolved it by calling putting the call to start(), pause(),... in onPrepared() method of OnPreparedListener() as below:
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
........
mediaPlayer.start();
....
songControlBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
............
}
});
}
});
Also try to release any media player that you do not need any more. For example, if you do not want to play the audio or video on background then you should call mediaPlayer.release() in onPause().
i tested below code. working fine
public class test extends Activity implements OnErrorListener, OnPreparedListener {
private MediaPlayer player;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("http://www.hubharp.com/web_sound/BachGavotte.mp3");
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
#Override
public void onPrepared(MediaPlayer play) {
play.start();
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
}
Some times file are encoded in a way that Android can't decode. Even some mp4 files can not be played. Please try a different file format (.3gp are played most of the time) and see..
You get this message in the logs, because you do something that is not allowed in the current state of your MediaPlayer instance.
Therefore you should always register an error handler to catch those things (as #tidbeck suggested).
At first, I advice you to take a look at the documentation for the MediaPlayer class and get an understanding of what that with states means. See: http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram
Your mistake here could well be one of the common ones, the others wrote here, but in general, I would take a look at the documentation of what methods are valid to call in what state: http://developer.android.com/reference/android/media/MediaPlayer.html#Valid_and_Invalid_States
In my example it was the method mediaPlayer.CurrentPosition, that I called while the media player was in a state, where it was not allowed to call this property.
above the picture,you can get the right way.
I solved both the errors (-19,0) and (-38,0) , by creating a new object of MediaPlayer every time before playing and releasing it after that.
Before :
void play(int resourceID) {
if (getActivity() != null) {
//Using the same object - Problem persists
player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
After:
void play(int resourceID) {
if (getActivity() != null) {
//Problem Solved
//Creating new MediaPlayer object every time and releasing it after completion
final MediaPlayer player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
if(length>0)
{
mediaPlayer = new MediaPlayer();
Log.d("length",""+length);
try {
mediaPlayer.setDataSource(getApplication(),Uri.parse(uri));
} catch(IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(length);
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
It was every much frustrated. So, I got solution which works for me.
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(file.getAbsolutePath());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
});
}
});
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
For me this worked
mp.seekTo(0);
mp.start();
I also got this error i tried with onPreparedListener but still got this error. Finally i got the solution that error is my fault because i forgot the internet permission in Android Manifest xml. :)
<uses-permission android:name="android.permission.INTERNET" />
I used sample coding for mediaplayer. I used in StreamService.java
onCreate method
String url = "http://s17.myradiostream.com:11474/";
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mp = new MediaPlayer();
AssetFileDescriptor afd = mContext.getAssets().openFd(fileName);
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepareAsync();
I have change setAudioStreamType to setAudioAttributes;
mediaPlayer.setAudioAttributes(AudioAttributes.Builder()
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
.setLegacyStreamType(AudioManager.STREAM_ALARM)
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
I am new in android programming and i had same error as this one. so i simply redefined the mp.createmediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI). It may not the true way to do it but it worked fined for me:
try {
mp = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI);
} catch (Exception e) {
e.printStackTrace();
}
mp.start();

Categories

Resources