android:play audio files using single mediaplayer

2019-03-05 03:05发布

问题:

i need to display images and play corresponding audio files one after the other.

i tried to create multiple media player objects but it shows error(1, -17)

so plz help guys i am running out of time.

Right now i have a handler which plays audio file and then get the duration of that audio file while playing another audio file this is my approach but i am unable to play some 10 files

below is my sample code

img.setBackgroundResource(R.drawable.d002_p001);
        d002_ae_p001 = MediaPlayer.create(this, R.raw.d002_ae_p001);
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                d002_ae_p001.start();
                xml();
            }
        },1000);

        d002_ae_p002 = MediaPlayer.create(this,R.raw.d002_ae_p002);
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                i++;
                img.setBackgroundResource(R.drawable.d002_p002);
                d002_ae_p002.start();
                xml();
            }
        },d002_ae_p001.getDuration()+2000);

EDITED THIS MY code

int image[] = {R.drawable.apple,R.drawable.boy,R.drawable.cat};

    String audio[]={"apple_v.mp3","boy_v.mp3","cat_v.mp3"};

    MediaPlayer mp = new MediaPlayer();

    AssetFileDescriptor descriptor;
            try {
                descriptor = getAssets().openFd(audio[i]);
                mp.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(),descriptor.getLength());
                descriptor.close();
                mp.prepare();
                mp.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mp.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer arg0) {
                    // TODO Auto-generated method stub
                    img.setImageResource(image[i]);
                    i++;
                    mp.start();
                }
            });

回答1:

Here is my suggestion:

First of all, put you MP3 files in assets not raw. This code will play from assets:

MediaPlayer mp = new MediaPlayer();

AssetFileDescriptor descriptor;
descriptor = getAssets().openFd( "filename.mp3" );
mp.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(),         descriptor.getLength() );
descriptor.close();
mp.prepare();
mp.start();

mp.setOnCompletionListener(
new OnCompletionListener(){
@Override 
public void onCompletion(MediaPlayer mp) {  
//code here to change your image, suggest having an array of filenames and incrementing
//each time you pass through. 
}
});

Hope that helps