Huy Than
Huy Than

Reputation: 1546

Android: MediaPlayer.setDataSource(FileDescriptor fd) vs MediaPlayer.setDataSource(FileDescriptor fd, long offset, long length)

I have created 3 Asset file descriptor of 3 sounds (put in res/raw)

AssetFileDescriptor afd1 = mContext.getResources().openRawResourceFd(R.raw.mp3_file_1);

AssetFileDescriptor afd2 = mContext.getResources().openRawResourceFd(R.raw.mp3_file_2);

AssetFileDescriptor afd3 = mContext.getResources().openRawResourceFd(R.raw.mp3_file_3);

Then I put them into an array:

    array.add(afd1);
    array.add(afd2);
    array.add(afd3);

Then I create an instance of MediaPlayer and let it play only the first sound in the array

MediaPlayer mp = new MediaPlayer();
mp.setDataSource(array.get(0).getFileDescriptor());
mp.prepare();
mp.start()

However, all the 3 sounds in the array are played. Then I tried to use setDataSource(FileDescriptor, long, long) instead of setDataSource(FileDescriptor fd), the mp plays ONLY the 1st sound in the array as I wanted.

AssetFileDescriptor afd = array.get(0);

mp.setDataSource(afd.getFileDescriptor(),
                afd.getStartOffset(), afd.getLength());

My question is what is the difference between the TWO setDataSource methods above? With the code I included here, why setDataSource(array.get(0)) plays all 3 sounds in the array?

Many thanks.

Upvotes: 2

Views: 1710

Answers (1)

StenSoft
StenSoft

Reputation: 9609

The second one is told length (and offset) while the first one plays as long as the file descriptor returns some data. Resources are usually stored in an archive so reading from the file descriptor continues past the first song where it finds the second song and then the third song.

Upvotes: 2

Related Questions