How to start a second media player ..? - java

I am developing an App where I want to play two mp3 files one is background music and another audio plays after 20 seconds.
mediaPlayer = MediaPlayer.create(this, R.raw.testsong_20_sec);
mediaPlayer1 = MediaPlayer.create(this,R.raw.sound3 );
private void buttonClick(){
if (buttonPlayStop.getText() == getString(R.string.play_str)) {
buttonPlayStop.setText(getString(R.string.pause_str));
try
{
mediaPlayer.start();
mediaPlayer1.start();
startPlayProgressUpdater();
}
catch (IllegalStateException e) {
mediaPlayer.pause();
}
}

Use MediaPlayer to play background music and SoundPool for everything else.

You can play two files in Mediaplayer by using this piece of code in a thread(don't use UI thread for this) :
mediaplayer = new MediaPlayer();
mediaplayer.reset();
//For media file 1
mediaplayer.setDataSource(dataSourceOne);
mediaplayer.prepare();
mediaplayer.start();
Thread.sleep(500);//Set the time as per your need.
//For media file 2
mediaplayer.reset();
mediaplayer.setDataSource(dataSourceTwo);
mediaplayer.setLooping(true);
mediaplayer.prepare();
mediaplayer.start();
As per the better implementation perspective, write an util class with all the common methods (play(),pause(),stop()) and call every method from your class based on the requirement using a thread.

Related

MediaPlayer loading sound from Uri not working

I have a simple voice recorder app. When the user records something it gets saved on the external storage and after that it gets played from there.
Everything works fine except on a Huawei P8 Lite smartphone with Android 6.
Here is how I play the sound:
Thread th=new Thread(new Runnable() {
#Override
public void run() {
try {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(view.getContext(), uri);
mp.prepare();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//send message to handler
}
});
th.start();
The Uri does exist at this moment and also the file does exist in the destination. Why is my mediaPlayer not playing anything? The permissions are given at this point where it tries to create the MediaPlayer so it should not be a permission issue.
All I get in the logcat is:
W/MediaPlayer-JNI: MediaPlayer finalized without being released
I/MediaPlayer: setDataSource(34, 0, 576460752303423487)
I/MediaPlayer: [HSM] stayAwake true uid: 10255, pid: 22592
E/MediaPlayer: error (-19, 0)
E/MediaPlayer: Error (-19,0)
Like I said it works fine on all other devices I tested (Android 10 & Android 9)
EDIT
Here is what I tried:
I created Emulators with every API level from API 18 to 30 and it works fine on every emulator.
I reseted my Huawei P8 Lite smartphone to factory settings.
I checked if the sound file is saved properly and if I can open and play it manualy when I navigate in the folder where it gets saved (it works perfectly so it has nothing to do with the code that saves the sound)
I really run out of ideas.
Hope someone can help, Thanks!
You need to player prepare asynchronously. player. prepare() replace with below code:
player.prepareAsync()

How to vibrate with sound

I am trying to add sound while vibration.
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(2000);
}
Vibration Applied successfully, but how to add sound while phone vibrate?
You can easily do that using MediaPlayer.
Firstly, Create an instance of MediaPlayer class:
MediaPlayer mediaPlayer = new MediaPlayer();
Then, set the source file, in order to this, firstly place the audio file in res/raw folder of your Project directory, then use this code:
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}");
Then play that file using this code:
mediaPlayer.prepare();
mediaPlayer.start();
Keep in mind that you have to put this code in try | catch block.
Now your whole code will be this:
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
// Initializing instance of Vibrator.
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Initializing instance of MediaPlayer.
MediaPlayer mediaPlayer = new MediaPlayer();
// Starting Vibration
v.vibrate(2000);
try {
// Setting the source of audio file.
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}"); // Fill the information accordingly.
mediaPlayer.prepare();
// playing audio.
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}

MediaPlayer delay 0.4 seconds for Bluetooth headset

I'm developing an application with playing audio. In several cases I change the AudioStreamType to AudioManager.STREAM_RING(is mode when music is playing both: speakers and headset). When I use Bluetooth headset, I have a small annoying delay.
So i was reading that Bluetooth has a buffer and and this is logical
, but how I can solve this? Also i tried to change buffer size or delay for mediaPlayer.
So, i create a mediaPlayer like as:
#Override
public void onInit() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setLooping(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
songManager = new SongsManager(context);
}
#Override
public void onPrepare() {
// prepare media player
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
absolutePathToPlayingSong = /*some place*/;
mediaPlayer.setDataSource(/*some place*/);
mediaPlayer.prepare();
mediaPlayer.setVolume(volumeLvl, volumeLvl);
}
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
}
then i just start player:
mediaPlayer.start();
So, i already tried:
to change a prepare() to prepareAsync() - probably it was tiny help, to may be i had a sound hallucinations. Unfortunately it broke a seekTo() in one place
added onPrepared() and start playing from listener - I not sure that it help
Give me please any advance^ how to fix delay for Bluetooth headset? I checked this device in YouTube application and it work great. So problem in my application. sorry my bad English!)
I have 2 target devices android 7.0(SDK 24) and android 4.2 (SDK 16)

Doing an audio loop on Android

I have a track I want to play 'megadeth', I'm calling it by:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.megadeth);
And playing it by using 'mp.start'.
And I just want to know, how can I get this audio mp3 to loop?
Before adding
mp.start();
Add
MediaPlayer mp = MediaPlayer.create(MainMenu.this, R.raw.megadeth);
mp.setLooping(true);
the mp.setLooping(true); automatically allows the raw file to be used over and over again.

Android media player stop playing while in background

I'm making music player app with simple functionality. But when I listen music on my phone with Android 6, sometimes music stops playing until I turn on display again with power button. Then next song is playing, so it seems like it's problem with loading next song. I tried to write new app just to test it out, for this purpose I used this tutorial:
https://code.tutsplus.com/tutorials/background-audio-in-android-with-mediasessioncompat--cms-27030
To this example I added ArrayList with paths to songs. In mediaPlayer onCompletionListener I increase track counter and load new song to media player.
My code:
private void initMediaPlayer() {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setVolume(1.0f, 1.0f);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer)
{
onTrackCompletion();
}
});
private void onTrackCompletion()
{
NextTrack();
Play();
}
private void NextTrack()
{
playlistPosition++;
if (playlistPosition == playlists.get(playlistCurrent).size){
playlistPosition = 0;
}
sendAction(ACTION_TRACK_NEXT);
if(mMediaPlayer.isPlaying()){
Pause();
}
loadSong();
Play();
}
private void loadSong()
{
String path = playlists.get(playlistCurrent).getPath(playlistPosition);
if(path == null || path == "")
{
return;
}
try
{
try
{
mMediaPlayer.setDataSource(path);
} catch( IllegalStateException e ) {
mMediaPlayer.release();
initMediaPlayer();
mMediaPlayer.setDataSource(path);
}
initMediaSessionMetadata();
} catch (IOException e) {
return;
}
try {
mMediaPlayer.prepare();
} catch (IOException e) {}
sendTrackData();
}
I don't know anymore why this doesn't work. In manifest I have WAKE_LOCK permission. I also set wake lock for Media player.
Edit:
Today I tried to move loading song into onPlayFromMediaId. I made broadcast from AutoActivity where is Media player to Main Activity and send back onPlayFromMediaId with path to song. But seems like this doesn't work either.I also find out that changing volume with buttons also wake up app.
Edit2:
I made many tests and added debug string in many places in code. And I found out that app stops at mediaplayer.prepare() until I trigger any action on phone (turn on display, volume up/down, click headset button). But I don't know how to fix this bug. I tried to use prepareAsync, but didn't help.
Unless you use foreground service, the system will kill your process and mediaplayer will stop.
below is a part from from a foreground service ( notification example).
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(this.getString(R.string.app_name)) // required
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{0L})
.setPriority(Notification.PRIORITY_HIGH);
int mId = 1489;
startForeground(mId, builder.build());
The above code is tested and working fine.

Categories

Resources