mardi 5 mai 2015

Play music synchronous using 3 MediaPlayer Objects on Android/Eclipse

What i have: I have implemented three MediaPlayer.Objects in my App. All Three are created using a thread:

protected void onResume() {
    // Threads
    mTT1 = new TrackThread(this, R.raw.audiofile1, 1, mHandler);
    mTT2 = new TrackThread(this, R.raw.audiofile2, 2, mHandler);
    mTT3 = new TrackThread(this, R.raw.audiofile3, 3, mHandler);
    // start thread
    mTT1.start();
    mTT2.start();
    mTT3.start();
    super.onResume();
}

"simplified" Code in the Thread for creating:

public class TrackThread extends Thread implements OnPreparedListener {
...
...
...
 public void run() {
    super.run();
            try {
                mMp.setDataSource(afd.getFileDescriptor(),
                        afd.getStartOffset(), afd.getDeclaredLength());
                mMp.prepare();
            } catch (IllegalArgumentException | IllegalStateException
                    | IOException e) {
                Log.e(TAG, "Unable to play audio queue do to exception: "
                        + e.getMessage(), e);
            }
      }

As I read in several Tutorials the "prepare()" methode takes a little bit of time to finish. Therefore i implemented a "Waiting loop" which waits until all MPs are prepared and created.

When "prepare and create" are done i enable the Start button and i want to start all 3 Mediaplayers SIMULTANEOUSLY.

I again use a Thread for dooing so:

public void onClick(View v) {
    // Button 1
    if (mBtn.getId() == v.getId()) {
                mTT1.startMusic();
                mTT2.startMusic();
                mTT3.startMusic();
    }

Code in the thread:

public class TrackThread extends Thread implements OnPreparedListener {
...
...
...

// start
public void startMusic() {
    if (mMp == null)
        return;
    mMp.start();
}

Please note that the code above is not the full code, but it should be enough to define my problem.

What i want, My problem:

All MPs should play their Music in Sync, unfortunately sometimes when i start the music, there is a time delay between them.

The MPs must start at the exact same time as the 3Audio-files must be played simultaneously (and exactly in sync)

What i have already tried:

+) using SoundPool: My Audio-files are to big(5Megabyte and larger) for SoundPool

+) seekTo(msec): i wanted to seek every MP to a Specific time: eg.: 0, but this did not solve the problem.

+) to reach more Programmers i also asked this question on: coderanch.com

I hope somebody can help me!

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire