Android mediaPlayer服务无法正常工作

时间:2018-01-07 01:30:47

标签: java android android-mediaplayer

我试图播放2个声音之一,correct.mp3或incorrect.mp3,它存储在我的资源文件夹中。这是我服务的代码:

public class MinesweeperSound extends Service {

    MediaPlayer player;

    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            String audioFile = null;
            audioFile = intent.getStringExtra("filename");
            AssetFileDescriptor afd = getAssets().openFd(audioFile);
            player = new MediaPlayer();
            player.setDataSource(afd.getFileDescriptor());
            player.prepare();
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mediaPlayer.release();
                }
            });
        }catch (IOException e){
            e.printStackTrace();
        }
        return Service.START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

这是我在Activity中如何称呼它:

Intent correctIntent = new Intent(getApplicationContext(), MinesweeperSound.class);
                    correctIntent.putExtra("filename", "correct.mp3");
                    startService(correctIntent);

由于某种原因它没有播放任何声音,任何帮助都很好,谢谢

3 个答案:

答案 0 :(得分:0)

您应该在调用prepare

之前设置prepare listener
  player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); } });
    player.prepare();

答案 1 :(得分:0)

MediaPlayer.prepare()是一种同步方法。如果您使用它,那么您不需要onPrepareListener。

否则使用

prepareAsync() 

而不是

prepare()

答案 2 :(得分:0)

我终于明白了。我需要为.setDataSource方法添加参数。这是工作代码:

MediaPlayer player = null;

    public int onStartCommand(Intent intent, int flags, int startId){
        try {
            String audioFile = null;
            audioFile = intent.getStringExtra(PowerUpUtils.MINESWEEPER_TILE_RESULT);
            AssetFileDescriptor afd = getBaseContext().getAssets().openFd(audioFile);
            player = new MediaPlayer();
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            player.prepare();
        }catch (IOException e){
            e.printStackTrace();
        }
        player.start();
        return Service.START_STICKY;
    }

同样,在try-catch块之后调用start()似乎是修复的一部分。