Android MediaPlayer.Create() returns null

谁说我不能喝 提交于 2019-12-17 20:48:56

问题


I am developing an Android App that plays some sounds. For that I am creating an object of MediaPlayer. Below is the code:

mp = MediaPlayer.create(this, R.raw.testSound);

Here mp is null for Android 2.3.3 (API Level 10), i tried with other versions of Android (2.1, 2.2 etc.) it works fine. However with Android 2.3.3 (API Level 10) MediaPlayer.create() call returns null.

The sound file (testSound.wav) is a wav file. I tried parsing the wav file to see if it is corrupted or not. It seems just fine. Also, I could play this sound file using Windows Media Player.

Here's the testSound.wav file: testSound.wav and below is the code in detail:

public MediaPlayer mp;

// OnCreate() funciton
mp = MediaPlayer.create(this, R.raw.testSound);
if(mp == null)   // mp is null for Android 2.3.3 on real device and on AVD both
  {
  Toast msg = Toast.makeText(getApplicationContext(), "Could not play sound",         
  Toast.LENGTH_LONG);
  msg.show();
  }

//SetMediaFileToPlay() is called on Click event of button
void SetMediaFileToPlay() 
{       
    AssetFileDescriptor afd;     
    Resources res = getResources();
    Log.d("In SetMediaFileToPlay %s", g_strFocusedImage.toString());
    switch (g_strFocusedImage)
    {
      case RESID_ALPHA1:
      afd = res.openRawResourceFd(R.raw.ik);
      if(mp != null)
      {
        mp.reset();
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),      
        afd.getLength());
      }  
      break;
      .........  //other cases
   }

 if(mp != null)
  {
    mp.prepare();
    mp.start();
  }

}

Please help. Thank You.


回答1:


Your file uses WAVE 8,000Hz MP3 8 kbit/s format, while android supports only 8- and 16-bit linear PCM: http://developer.android.com/guide/appendix/media-formats.html.

Try fixing your file.




回答2:


It can happen that it returns null because the device doesn't support playing audio i.e watch.

To check if device supports MediaPlayer you can do a null check on MediaPlayer.create()

I found it on google santa-tracker app



来源:https://stackoverflow.com/questions/11811466/android-mediaplayer-create-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!