play multiple mp3 files with delay - android

I need the method that my app run multiple mp3s. Each mp3 must play after previous mp3.
I created method that play sound
void PlaySentence(String path){
try {
AssetFileDescriptor afd = getAssets().openFd(path);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
}
catch (Exception ex)
{
if (BuildConfig.DEBUG)
Log.d(TAGName, ex.getMessage());
}
}
Then I call that function in OnCreate. I used while loop for playing all mp3 files. But sound mixed to each other. If I use loops and isPlaying method the application didn't respond.
while (currentMp3<totalMp3) {
if (!player.isPlaying()) {
PlaySentence();
}
}
Also I use below method for avoid of mixing sounds. It work for one mp3
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
PlaySentence();
}
});
What is the best solution to do that?

You should use setOnCompletionListener, but declare your player as a class member, initalize it in onCreate, and don't create a new one for each mp3. PlaySentence should be something as:
void PlaySentence(String path){
try {
AssetFileDescriptor afd = getAssets().openFd(path);
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
}
catch (Exception ex)
{
if (BuildConfig.DEBUG)
Log.d(TAGName, ex.getMessage());
}
}

Related

When using MediaPlayer, sometimes it does not sound

for recording file output, I use MediaPlayer.
usually, When I button clicked, start media file.
but, sometime not sound play.
/MediaPlayer: mediaplayer went away with unhandled events
W/MediaPlayer-JNI: MediaPlayer finalized without being released
at first I think before the voice file is finished, when clicked button occur this problem.
but even if I press the button repeatedly, sometime not sound play.
source.
player = new MediaPlayer();
player.reset();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.reset();
AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getResource().openRawResourceFd(R.raw.sound);
player.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (player != null) {
player.stop();
player.release();
}
}
});
How to fix sometimes not sound play when i button clicked?
thanks.
There's no reason to call MediaPlayer.release() if it will be used again, as calling reset() will release all the memory & codecs that are in use.
init:
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
}
});
Handling button clicks:
void onButtonClicked() {
player.reset();
AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getResource().openRawResourceFd(R.raw.sound);
player.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
player.prepare();
player.start();
}

Sound:Should have subtitle controller already set

I am having an odd issue where my audio file sometimes plays and sometimes does not play.
The catch is that when it decides to not play, the LogCat gives me this message:
Should have subtitle controller already set
This is my code to play the sound:
public void sound(){
//store the sound file name
String filename=f_fruit_ar.m4a;
//All sounds stored in assets folder
try{
AssetFileDescriptor afd = getAssets().openFd(filename);
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
I think the problem is your not releasing the resources once player is finished playing you need to release the resources.
EXAMPLE:
public void sound(){
//store the sound file name
String filename=f_fruit_ar.m4a;
//All sounds stored in assets folder
try{
AssetFileDescriptor afd = getAssets().openFd(filename);
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}

Can't play MediaPlayer onCreate

I have an app where I want, as soon as it starts, a little background music (opa gangam style!) to be played (from the sd card). I use the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = new MediaPlayer();
String filePath = Environment.getExternalStorageDirectory().getPath() + "/mymusic/gangamstyle.mp3";
try {
mp.setDataSource(filePath);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
But when I test it, no music is played. I see everything is ok however. What could I do wrong? Thanks a lot
You have to use setOnPreparedListener in order to know when the media player is ready to play:
MediaPlayer player = new MediaPlayer();
player.setDataSource(filePath);
player.setVolume(100, 100);
player.setLooping(false);
player.setOnPreparedListener(new OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
});
player.prepare();
There is some problem in your file path. Media player gives this kind of error when the file path is not correct. So, Please check your file path and then try it.

How can I play a series of short mp3 files with no gap between them in Android?

I have a lot of short .mp3 files that I want to play one after the other.. I tried to use onCompletion event and start the next mp3, though this causes a brief gap between the 2 mp3s..
Here is the code:
void StartSound() {
mediaplayer = MediaPlayer.create(this, Uri.parse(FILE_PATH + counter + ".mp3"));
try {
mediaplayer.start();
mediaplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
counter++;
try {
mp.reset();
mp.setDataSource(FILE_PATH + counter + ".mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mp.start();
}
});
} catch (Exception e) {
}
}
Is there a work around to this issue?
There's a workaround, but whether it's worth the trouble is up to you.
The basic idea is to decode the MP3 files to a PCM buffer, stitch them together in a byte array, and play with an AudioTrack. Seamless MP3 playback doesn't really exist with MediaPlayer. This could be a pain in the ass, though, and memory problems are likely if you're talking about full songs. For short clips, it may work, but SoundPool might be the better option.
If you're just trying to narrow the gap a bit, you can try preparing the following MediaPlayer objects before onCompletionListener. Instead of waiting to be done, prepare the next two so you can start playback faster. Then when you hit onCompletion, you can just flip which object you're using and start(). Crude double buffering, in a way.
Try this:
public class MainActivity extends Activity
{
private int[] tracks = {R.raw.explosion,R.raw.pianothingy_one,R.raw.car_horn_x};
int mCompleted = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = MediaPlayer.create(this, tracks[0]);
mp.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mCompleted++;
mp.reset();
if (mCompleted < tracks.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted>=tracks.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp.release();
mp = null;
}
}
});
mp.start();

Media Player delays to start

My media player delays its start when kept idle for some time, also some time it does not play the audio.
Earlier I used setDataSource(), but this time I am using create().
For reference this is the code I am using:
AssetFileDescriptor afd = _context.getResources().openRawResourceFd(this._soundResource.get(this._toBePlayed));
mp = new MediaPlayer();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
}
});
mp.prepareAsync();
I also had the delay problem for start(). I fixed it with mp.seekTo(0) in onPrepared like this:
mp.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mp.seekTo(0);
mp.start();
}
});
I use a FileInputStream. You didn't set the AudioStreamType. Here is how I setup my MediaPlayer.
public void setupMediaPlayer(){
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
fis = new FileInputStream(tempFilePath);
mp.setDataSource(fis.getFD());
mp.prepare();
mp.setOnPreparedListener(this);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
tempFilePath is the path to the file.
I also implement setOnPreparedListener in this class which makes your code a lot more readable in my opinion.
Also Great link to reference: MediaPlayer State Diagram
I think if you would change
mp.prepareAsync();
to
mp.prepare();
and put
mp.start();
after the mp.prepare(); your code will work. Give it a try.

Categories

Resources