0

我正在制作一个摇篮曲应用程序。最初,我的 /res/raw 文件夹中有两首曲目。在完成第一首曲目时,我希望它播放下一首曲目。我使用 onCompletionListener 做到了这一点。但它显示强制关闭错误。下面是我的代码。那么谁能告诉我该怎么做?

public class PlayRandom extends Activity implements OnCompletionListener{
        MediaPlayer mp;
    int rnum;
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playrandom);
                mp.setOnCompletionListener(this);
        mp = MediaPlayer.create(this, R.raw.lullaby1);
        mp.start();     
    }
    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        mp.stop();
    }
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        File pdfFile = new File("res/raw/lullaby2.mp3");
        Uri path = Uri.fromFile(pdfFile);
        mp.stop();
        try{
            mp.setDataSource(getApplicationContext(), path);
        mp.prepare();
        mp.start();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
}

我试过了,但仍然无法正常工作。这意味着 OnClickListener 有问题。

public class PlayRandom extends Activity implements OnCompletionListener{
    MediaPlayer mp;
int rnum;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.playrandom);
            mp.setOnCompletionListener(this);
    mp = MediaPlayer.create(this, R.raw.lullaby1);
    mp.start();     
}
@Override
public void finish() {
    // TODO Auto-generated method stub
    super.finish();
    mp.stop();
}
public void onCompletion(MediaPlayer mp) {
    // TODO Auto-generated method stub
    Toast.makeText(this,"Yuppieee!!", Toast.LENGTH_SHORT);
}

}

4

1 回答 1

2

用于AssetFileDescriptor 从原始文件夹播放文件:

   AssetFileDescriptor afdes = getAssets().openRawResourceFd(R.raw.lullaby2);
    mp.reset();
    mp.setDataSource(afdes.getFileDescriptor(), afdes.getStartOffset(), afdes.getLength());
    mp.prepare();
    mp.start();
于 2012-06-19T11:58:17.087 回答