Android MediaPlayer not preparing. Error (1, -4)

£可爱£侵袭症+ 提交于 2019-12-12 06:36:44

问题


So I've been trying to make a simple sound effect app for android. Here is the relevant code:

public static final String LOG_TAG = "BCA";

public MediaPlayer mp;

@Override
public void onCreate(Bundle savedInstanceState) 
{
        Log.v(LOG_TAG, "creating");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_list);

    mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        Log.v(LOG_TAG, "set stream type");
    playSound();
}

public void playSound()
{
    try {
        mp.setDataSource("R.raw.sound1");
            Log.v(LOG_TAG, "set data source");
        mp.setOnPreparedListener(this);
        mp.setOnErrorListener(this);
        mp.prepareAsync();
            Log.v(LOG_TAG, "preparing");
    } 
    catch (IllegalArgumentException e) {
        e.printStackTrace();
    } 
    catch (IllegalStateException e) {
        e.printStackTrace();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }
}

public void onPrepared(MediaPlayer mediaPlayer)
{ 
                Log.v(LOG_TAG, "finished preparing; starting");
    mp.start();
        Log.v(LOG_TAG, "started music");
}

public boolean onError(MediaPlayer mp, int e, int f)
{
        Log.v(LOG_TAG, "There was an error");
        Log.v(LOG_TAG, mp + " " + e + " " + f);
    mp.reset();
    return true;
}

Basically it gets to the set "set data source" tag but never finishes preparing. the error code is (1, 4) the 1 apparently being an unknown error. I have used multiple sound files, one of which I know works as the player works when just using the mp.create( etc... )

I'm not sure what's going on here

Thanks in advance

EDIT: So I followed the example of the link that Alexis Cartier gave and now there are no errors. However, the FileinputStream never finishes. The program just seems to stall. Here is the new code:

public void playMusic()
{
    File file = new File("R.raw.music1");
        Log.v(LOG_TAG, "set file");
    try {
            Log.v(LOG_TAG, "in try block");
        FileInputStream is = new FileInputStream(file);
            Log.v(LOG_TAG, "set file input stream");
        mp.setDataSource(is.getFD());
            Log.v(LOG_TAG, "set data source");
        mp.setOnPreparedListener(this);
        mp.setOnErrorListener(this);
            Log.v(LOG_TAG, "set on prepared/error listeners");
        mp.prepareAsync();
            Log.v(LOG_TAG, "preparing");
    } 

回答1:


See the answer of this question to modify your code : MediaPlayer.setDataSource causes IOException for valid file

But you can't do mp.setDataSource("R.raw.sound1");



来源:https://stackoverflow.com/questions/11970574/android-mediaplayer-not-preparing-error-1-4

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