1

我正在开发一个小测验应用程序,我想根据用户是否正确回答问题来播放声音。

我在“assets/”中有很多声音文件。

我想做的是只播放其中一种声音。我已经能够播放声音,但不仅是一种声音,两种声音(正确和错误)都一个接一个地播放。

我怎么能只玩一个?这是我的来源:

public void audioPlayer(){
    //set up MediaPlayer    
    mp = new MediaPlayer();

    try {
        String mp3File = "correct.mp3";
        AssetManager assetMan = getAssets();
        FileInputStream mp3Stream = assetMan.openFd(mp3File).createInputStream();

        mp.setDataSource(mp3Stream.getFD());
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
4

1 回答 1

1

将您的声音文件(即失败和掌声)放入原始文件夹并使用以下代码:

private AssetFileDescriptor sPlaySoundDescriptor = null;
private AssetFileDescriptor sFailSoundDescriptor = null;
private MediaPlayer mp = null;
public static final int FAIL_SOUND = 1;
public static final int APPLAUSE_SOUND = 2;

public void audioPlayer(int soundType){
    //set up MediaPlayer    
    mp = new MediaPlayer();
    AssetFileDescriptor soundFileDescriptor = null;
    try {
        if (sFailSoundDescriptor == null) {
            sFailSoundDescriptor = context.getResources().
                    openRawResourceFd(R.raw.fail);
        }
        if (sApplauseSoundDescriptor == null) {
            sApplauseSoundDescriptor = context.getResources().
                    openRawResourceFd(R.raw.applause);
        }
        switch (soundType) {
            case FAIL_SOUND:
                soundFileDescriptor = sFailSoundDescriptor;
                break;
            case APPLAUSE_SOUND:
                soundFileDescriptor = sApplauseSoundDescriptor;
                break;
        }
        mp.reset();
        mp.setDataSource(soundFileDescriptor.getFileDescriptor(),
                        soundFileDescriptor.getStartOffset(),
                        soundFileDescriptor.getDeclaredLength());
        mp.prepare();
        mp.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer player) {
                player.seekTo(0);
                player.start();
            }
        });  
    } catch (Exception e) {
        e.printStackTrace();
    }
}
于 2013-05-05T06:37:46.443 回答