something about android mp3 play - android

#Override
protected void onResume() {
playOrderSound();
super.onResume();
}
private void playOrderSound(Context context){
player= MediaPlayer.create(context, R.raw.order);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.start();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.reset();
player.release();
}
});
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
player.start();
return false;
}
});
}
I put the sound source in the raw directory and use mediaPlayer to play it.When the server send message to me.I start a new activity and play the mp3 resource,but it does't work.
the new activity start with lauchmode singletask.

Try this Playing Well
#Override
protected void onResume() {
super.onResume();
playOrderSound(Mainactivity.this);
}
private void playOrderSound(Context context){
player = MediaPlayer.create(context, R.raw.acc);
player.start();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.reset();
player.release();
}
});
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
player.start();
return false;
}
});
}
protected void onDestroy() {
super.onDestroy();
player.stop();
}

Related

How to fix IllegalStateException in Mediaplayer

I have a listview and MediaPlayer created in OnItemClick.
listSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Song song = mAdapter.getItem(position);
mPlayer = MediaPlayer.create(MainActivity.this, song.getmSongResourceId());
if (mPlayer != null) {
mPlayer.release();
}
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener () {
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.start();
mPlayer.pause();
controller.show(0);
}
});
mPlayer.start(); //error here
controller.show(0);
}
});
#Override
public void start() {
mPlayer.start();
}
#Override
protected void onStop() {
super.onStop();
mPlayer.pause();
controller.hide();
}
When ckick on item activity close. Here is logcat:
java.lang.IllegalStateException
at android.media.MediaPlayer._start(Native Method)
at android.media.MediaPlayer.start(MediaPlayer.java:1228)
at com.....MainActivity$2.onItemClick(MainActivity.java:432)
at android.widget.AdapterView.performItemClick(AdapterView.java:314)
at android.widget.AbsListView.performItemClick(AbsListView.java:1162)
at java.lang.reflect.Method.invoke(Native Method)
MainActivity.java:432 is mPlayer.start();.
What is IllegalStateException, and how can fix it? You may say my post is this post duplicate, but I'm not sure how to apply it solutions to my code.
Try
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener () {
#Override
public void onCompletion(MediaPlayer mp) {
mp.start();
mp.pause();
controller.show(0);
}
});

2 media services being played simultaneously

After pressing back button on MainActivity (which calls it's onDestroy()), the media plays in the background (using foreground service).
But after opening the app again ((which calls it's onCreate()), and if I try to play another song, the first song is not stopped. Both songs play together. How do I solve this?
Any help is appreciated.
This is my MusicService class:
public void onCreate() {
super.onCreate();
Log.i(TAG3, "onCreate");
songPosn=0;
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
player = new MediaPlayer();
initMusicPlayer();
rand=new Random();
}
//initializes the MediaPlayer class
public void initMusicPlayer(){
Log.i(TAG3, "initMusicPlayer");
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Song> theSongs){
songs=theSongs;
}
//We will call this when the user picks a song from the list.
public void setSong(int songIndex){
songPosn=songIndex;
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
//Let's now set the app up to play a track
public void playSong(){
Log.i(TAG3, "playSong");
player.reset();
//get song
Song playSong = songs.get(songPosn);
songTitle=playSong.getTitle();
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
public void playPrev(){
songPosn--;
if(songPosn<0) songPosn=songs.size()-1;
playSong();
}
//skip to next
public void playNext(){
if(repeat){playSong();}
else if(shuffle){
int newSong = songPosn;
while(newSong==songPosn){
newSong=rand.nextInt(songs.size());
}
songPosn=newSong;
playSong();
}
else{
songPosn++;
if(songPosn>=songs.size()) songPosn=0;
playSong();
}
}
public int getPosn(){
return player.getCurrentPosition();
}
public int getDur(){
return dr;
}
public boolean isPng(){
return player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
public void seek(int posn){
player.seekTo(posn);
}
public void go(){
player.start();
}
public void setShuffle(){
if(shuffle) shuffle=false;
else {shuffle=true;repeat=false;}
}
public void setRepeat(){
if(repeat) repeat=false;
else {repeat=true;shuffle=false;}
}
//When the MediaPlayer is prepared, the onPrepared method will be executed.
#Override
public void onPrepared(MediaPlayer mp) {
Log.i(TAG3, "onPrepared");
//start playback
mp.start();
dr = player.getDuration();
Intent notIntent = new Intent(this, MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing").setContentText(songTitle);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
#Override
public void onCompletion(MediaPlayer mp) {
Log.i(TAG3, "onCompletion");
if(player.getCurrentPosition()>0){
mp.reset();
playNext();
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.i(TAG3, "onError");
mp.reset();
return false;
}
#Override
public void onAudioFocusChange(int focusChange) {
if(focusChange<=0) {
//LOSS -> PAUSE
player.pause();
} else {
//GAIN -> PLAY
player.start();
}
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG3, "onBind");
return musicBind;
}
#Override
public boolean onUnbind(Intent intent){
Log.i(TAG3, "onUnbind");
return false;
}
#Override
public void onDestroy() {
Log.i(TAG3, "onDestroy");
mAudioManager.abandonAudioFocus(this);
stopForeground(true);
}
Note; I had removed player.stop(); player.release(); from the onUnbind() since the playback gets stopped on pressing backbutton on MainActivity.
The back button should not call onDestroy when pressed.
I found it here:
https://stackoverflow.com/a/5868534/6737655

How to return state of media player?

I'm trying to return the current state of the media player because I want to check that the media player has not loaded a song yet so I can provide a popup to choose an audio file.
Code in other class
public Sound(int buttonID, Activity _activity) {
super();
this.activity = _activity;
button = (Button) activity.findViewById(buttonID);
mp = new MediaPlayer();
}
Code to check if an audio file is loaded
sound.button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(//no audio file loaded){
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivityForResult(intent, PICK_AUDIO_REQUEST);
}
else if(sound.mp.isPlaying()) {
sound.mp.pause();
}
else{
sound.mp.seekTo(0);
sound.mp.start();
}
}
});
Using the answer, this is the code I came up with:
sound.button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sound.mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
isPrepared = true;
}
});
if(!isPrepared){
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivityForResult(intent, PICK_AUDIO_REQUEST);
}
else if(sound.mp.isPlaying()) {
sound.mp.pause();
}
else{
sound.mp.seekTo(0);
sound.mp.start();
}
}
});
Perhaps the following could help...
MediaPlayer.setOnBufferingUpdateListener(...);
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
//while MediaPlayer's buffer been update
}
MediaPlayer.setOnPreparedListener(...);
public void onPrepared(MediaPlayer mp)
{
//while MediaPlayer is ready to play
}
MediaPlayer.setOnCompletionListener(...);
public void onCompletion(MediaPlayer mp)
{
//while MediaPlayer played to the end
}
MediaPlayer.setOnErrorListener(...);
public boolean onError(MediaPlayer mp, int what, int extra)
{
//while MediaPlayer has error ocurred
}
Also, your class must implement OnAudioFocusChangeListener, and create the following method
public boolean requestAudioFocus()
{}
public boolean abandonAudioFocus()
{}
public void onAudioFocusChange(int focusChange)
{}
You may considered to put your MediaPlayer into a Service class.
I'm afraid that there is no such method. You have to check it yourself. It's not too hard to follow MeidaManager state with the MediaPlayer's StateDiagram. The easiest way is to declare a boolean flag isPrepared / isReadyToPlay and set it to true in onPrepared() callback of the OnPreparedListener.

MediaPlayer: error (-19, 0)

I tried all the solutions provided in this site & still i am getting this error.Don't know why it happen! please help me.
Here my code.
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.square);
mediaPlayer.setOnErrorListener(MainActivity.this);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mWinMusic[blocks].release();
}
});
public boolean onError(MediaPlayer mp, int what, int extra) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.square);
mp.start();
return true;
}
Create player like this and add mediaPlayer.prepare(); and when ready then start in onPrepared()
public class MainActivity extends Activity {
MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.square);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(MainActivity.this, "Some problem ", Toast.LENGTH_LONG).show();
return false;
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(MainActivity.this, "track completed", Toast.LENGTH_SHORT).show();
//mWinMusic[blocks].release();
}
});
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Some problem " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}

How to prepare mediaplayer in android while another playing?

I using MediaPlayerto play video from http stream is any solution to prepare second media player with another http url while first one still playing?
I want to play two videos without black screen between them, when first one end second start immediately.
Here is my code:
public class VideoActivity extends Activity implements SurfaceHolder.Callback {
private MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SurfaceView playerSurfaceView;
private String videoSrc = "http://192.168.1.101:8090/api/video/";
private String android_id;
private MediaPlayer next;
private static boolean firstCall = true;
private String secondVideoSrc = "http://192.168.1.101:8090/api/secondvideo/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
GetDeviceId();
videoSrc += android_id;
secondVideoSrc += android_id;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
prepareVideoPlayer();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private void GetDeviceId() {
android_id = Settings.Secure.getString(getBaseContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
}
private void prepareVideoPlayer() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(this, Uri.parse(videoSrc));
mediaPlayer.setScreenOnWhilePlaying(true);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if(firstCall) {
mediaPlayer.start();
firstCall = false;
}
new AsyncPrepareNext().execute();
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.start();
}
});
}
catch(Exception ex) {
}
}
private void prepareNext() {
try {
next = new MediaPlayer();
next.setDisplay(surfaceHolder);
next.setDataSource(this, Uri.parse(secondVideoSrc));
next.setScreenOnWhilePlaying(true);
next.prepareAsync();
next.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
next.setAudioStreamType(AudioManager.STREAM_MUSIC);
next.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
}
catch(Exception ex) {
}
}
private class AsyncPrepareNext extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
prepareNext();
return null;
}
}
}
When i run this first video starts for 2 or 3 seconds and then stop with some errors like media server died, audio flinger died, error (100,0), error (38,0)
You'll probably need to implement the OnPreparedListener() and OnCompletedListener() to accomplish this and you might need 2 media players for it as well.
#Override
public void onPrepared(MediaPlayer mp){
// Set Video Source for second video
mp.setDataSource(path);
// Prepare second video
mp.prepareAsync();
}
#Override
public void onCompletion(MediaPlayer mp){
// Start second video here
mp.start();
}
and set them like this:
mediaPlayer.setOnPreparedListener(new OnPreparedListener());
mediaPlayer.setOnCompletedListener(new OnCompletionListener());

Categories

Resources