0

在下面运行代码时我有两个问题

  1. Mediaplayer 没有停止,因为它是一种方法 mp.isPlaying() 总是返回 false。
  2. 有时我会收到无效的状态异常。
try {
    String[] alerts = getResources().getStringArray(R.array.mp3files);
    int ch;
    StringBuffer fileContent = new StringBuffer("");
    FileInputStream fis = openFileInput("alertNo");
    byte[] buffer = new byte[1];
    int length;
    while ((length = fis.read(buffer)) != -1) {
        fileContent.append(new String(buffer));
    }
    String data = new String(fileContent);
    int position = Integer.parseInt(data);
    //m.setVolume(100, 100);
    if (m.isPlaying()) {
    m.stop();
    m.release();
    }
    AssetFileDescriptor descriptor = 
        MySettings.this.getAssets().openFd(alerts[position] + ".mp3");
    m.setDataSource(descriptor.getFileDescriptor(), 
        descriptor.getStartOffset(), descriptor.getLength());
    descriptor.close();
    m.prepare();
    m.start();
} catch (Exception e) {
    e.printStackTrace();
}
4

2 回答 2

1

检查文档,一旦调用发布,就无法重用该对象。您将不得不创建另一个 Mediaplayer。

引。

 after release() is called, it is in the End state

一旦 MediaPlayer 对象处于 End 状态,就不能再使用它,也无法将其恢复到任何其他状态。

所以m用新的 Mediaplayer 重新初始化对象或重置它

于 2012-09-18T07:59:18.313 回答
0

感谢nandeesh,我通过这种方式做到了:)

try {
                MediaPlayer m = new MediaPlayer();
                String[] alerts = getResources().getStringArray(R.array.mp3files);
                int ch;
                StringBuffer fileContent = new StringBuffer("");
                FileInputStream fis = openFileInput("alertNo");
                byte[] buffer = new byte[1];
                int length;
                while ((length = fis.read(buffer)) != -1) {
                    fileContent.append(new String(buffer));
                }
                String data = new String(fileContent);
                int position = Integer.parseInt(data);
                //m.setVolume(100, 100);
                if (m.isPlaying()) {
                    m.stop();
                    m.release();
                    m = new MediaPlayer();
                }
                AssetFileDescriptor descriptor = MySettings.this.getAssets().openFd(alerts[position] + ".mp3");
                m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
                descriptor.close();

                m.prepare();
                m.start();
                CustomizeDialog dialog = new CustomizeDialog(MySettings.this,m);
                dialog.setTitle("Alert Test!");
                dialog.setMessage("Please Press \"Yes\" if you hear the alert sound now. if you don't here an alert, click \"No\" ");
                dialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
于 2012-09-18T08:17:01.583 回答