I need help to set duration of MediaPlayer on start activity.
I have tried using seekTo() but its not working correctly.
Here is what I'm doing:
protected void Player(String bURL, int seekTo){
btn = (Button) findViewById(R.id.playpauseBtn);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(bURL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mediaPlayer.isPlaying()) {
if (seekTo != 0) {
mediaPlayer.seekTo(seekTo);
}
mediaPlayer.start();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Try to modify to this:
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying()) {
if (seekTo != 0) {
mp.seekTo(seekTo);
}
mp.start();
}
}
});
mediaPlayer.setDataSource(bURL);
mediaPlayer.prepareAsync();
Related
I can not reproduce the sound when pressing the button, any possible solution? I use SDK 30.
if(playingSongPosition !=position)
imageView.setImageResource(R.drawable.icon_play);
else
imageView.setImageResource(R.drawable.icon_pause);
constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(TrimAudioActivity.this,SelectSectionActivity.class);
intent.putExtra(getResources().getString(R.string.music_file_name),getItem(position));
intent.putExtra(getResources().getString(R.string.selected_song_uri),getUri(position));
intent.putExtra(getResources().getString(R.string.duration),getDuration(position));
startActivity(intent);
}
});
final View finalView = view;
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentTrack=position;
if(prevTrack==currentTrack){
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
mediaPlayer.seekTo(0);
imageView.setImageResource(R.drawable.icon_play);
playingSongPosition =-1;
}else{
mediaPlayer.start();
imageView.setImageResource(R.drawable.icon_pause);
}
}else{
if(prevTrack!=-1) {
isCallExplicit=true;
// Toast.makeText(ContactsRingtoneActivity.this, "prev:"+prevTrack+" current:"+currentTrack, Toast.LENGTH_SHORT).show();
ImageView prevImageView = (ImageView) getView(prevTrack, prevView, parent).findViewById(R.id.imageViewPlayPauseMyAudioItem);
prevImageView.setImageResource(R.drawable.icon_play);
isCallExplicit=false;
}
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
playingSongPosition =position;
imageView.setImageResource(R.drawable.icon_pause);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
imageView.setImageResource(R.drawable.icon_play);
mediaPlayer.seekTo(0);
playingSongPosition =-1;
}
});
try {
mediaPlayer.setDataSource(TrimAudioActivity.this,getUri(position));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
prevTrack=currentTrack;
prevView= finalView;
}
}
});
return view;
}
}
#Override
protected void onStop() {
super.onStop();
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playingSongPosition =-1;
}
}
I have a problem with the Android MediaPlayer. As soon as a new sound file is clicked by user input, the old one does not stop, so all audio files overlap.
I already tried common methods like MediaPlayer.stop(); and
MediaPlayer.release();
These methods always result in an app crash, although they are called in the correct order
public void Abspielen(String Datei) {
try {
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Abspielen("filename");
}
I worked out the following solution:
public void Abspielen(String Datei) {
try {
stopKnopf = findViewById(R.id.fab2);
stopKnopf.show();
try {
if (AndreasPlayer.isPlaying()) {
AndreasPlayer.reset();
}
} catch (Exception ex) {
}
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
stopKnopf.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
AndreasPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
Currently, I'm working on my simple android studio script, and I must use volume down while the mobile screen is locked.
Please, take a look at my script:
public class MainActivity extends AppCompatActivity {
public MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BroadcastReceiver vReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
}
};
registerReceiver(vReceiver, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
return true;
}
return super.onKeyDown(keyCode, event);
}
public void initAudio(final Context context, String url) {
if (mediaPlayer == null) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
killMediaPlayer();
}
});
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
}
}
public void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
What should I do to fix this issue? There are no errors, the script only works when I'm with my screen unlocked.
Can you help me with this?
Thank you very much.
It works for a few buttons, but when I tap about 6 then only some of them work. The ones that don't work give the error (1, -19). I do the media player state wrapper set up, so if I need to use that to get states of my "mp"s, let me know.
public class SoundFile {
public SoundFile(final Activity activity, final String soundfile, int imgButtonId, ArrayList<MediaPlayerStateWrapper> mps) {
this.mp = new MediaPlayerStateWrapper();
try {
this.afd = activity.getAssets().openFd(soundfile + ".mp3");
} catch (IOException e) {
e.printStackTrace();
}
this.allMps = mps;
mps.add(this.mp);
this.position = (ImageButton) activity.findViewById(imgButtonId);
this.position.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepareAsync();
mp.start();
}catch (Exception ex){
ex.printStackTrace();
}
....
You have to add an onPreparedListener. Here is what I did and it worked.
try {
mp = new MediaPlayer();
mp.reset();
try {
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
}
});
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mpm) {
mpm.start();
mp.start();
}
});
mp.prepareAsync();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
}
I've set MediaPlayer to play different songs. However, when I try to close the Application, the Activity gets closed, but the song still run in the Background. Here is how I've coded it!
try {
mp.setDataSource(text);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
mp.setVolume(0.4f, 0.4f);
songPlayer.setDataSource(song);
songPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer songPlayer) {
songPlayer.start();
}
});
songPlayer.prepare();
songPlayer.setLooping(true);
voicePlayer.setDataSource(voice);
voicePlayer.setLooping(true);
voicePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer voicePlayer) {
voicePlayer.start();
}
});
voicePlayer.prepare();
voicePlayer.setVolume(0.5f,0.5f);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (IllegalMonitorStateException e)
{
e.printStackTrace();
}
//THIS IS WHERE I THINK THE ERROR IS :
//WHERE `mp` IS LOOPED WITH DELAY OF 5000ms
try {
final Handler hlr = new Handler();
final Runnable looper = new Runnable() {
#Override
public void run() {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
}
mp.start();
}
};
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
hlr.postDelayed(looper, 5000);
}
});
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
}
}
And there is also One method which restarts the activity after a specified time. And the code for that Activity is :
public void snoozeup(View view)
{
SharedPreferences sa = getSharedPreferences("SnoozeList", Context.MODE_PRIVATE);
int snox = sa.getInt("SnoozeX",0);
if(snox==2) {
Handler handler = new Handler();
Runnable x = new Runnable() {
#Override
public void run()
{
Intent intent = new Intent(Time_Date.this, Time_Date.class);
intent.putExtra("finisher", state);
startActivity(intent);
}
};
handler.postDelayed(x, 120000);
}
else
{
Handler handler = new Handler();
Runnable x = new Runnable() {
#Override
public void run() {
startActivity(new Intent(Time_Date.this, Time_Date.class));
}
};
handler.postDelayed(x, 180000);
}
try
{
if (mp != null && mp.isPlaying())
{
Log.d("TAG------->", "mp is running");
mp.stop();
Log.d("TAG------->", "mp is stopped");
mp.reset();
mp.release();
Log.d("TAG------->", "mp is released");
mp=null;
}
if (voicePlayer != null && voicePlayer.isPlaying()) {
Log.d("TAG------->", "voiceplayer is running");
voicePlayer.stop();
Log.d("TAG------->", "voiceplayer is stopped");
voicePlayer.release();
Log.d("TAG------->", "voiceplayer is released");
}
if (songPlayer != null && songPlayer.isPlaying()) {
Log.d("TAG------->", "songplayer is running");
songPlayer.stop();
Log.d("TAG------->", "songplayer is stopped");
songPlayer.release();
Log.d("TAG------->", "songplayer is released");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finish();
}
The problem is with mp . Other instances of MediaPlayer gets stopped. But not mp. And sadly, Can't see any error in logcat as well. So where am I doing wrong? Any help will be appreciated.
In order to stop the music you should put this code in the onPause() method.
This method can be overrided from your class that inherite from Activity
#Override
protected void onPause() {
super.onPause();
mp.stop
}
You can also take a look at Managing the Activity Lifecycle to better understand how an activity is managed by Android.
You are destroying your activity, but you need to stop/destroy your media player too. Please write down the following code in your activity.
#Override
public void onDestroy() {
super.onDestroy();
if (mp!= null) {
//destory ur object here.
}
}
Put in either onPause() or onDestroy() Example:
#Override
protected void onPause() {
super.onPause();
mp.stop();
}