播放所选音乐作为游戏的背景音乐

时间:2017-02-12 11:35:24

标签: android android-studio

我想为Android创建一个游戏,用户从他的库中选择音乐,然后在游戏运行时在背景上播放,直到失败。

这是我的代码,当它被选中时播放歌曲,但是当我按下OK按钮时它不会继续播放

public class MainActivity extends AppCompatActivity {

MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button openFile = (Button) this.findViewById(R.id.openFile);
    openFile.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, 10);
        }

    });
    Button play = (Button) this.findViewById(R.id.button2);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(resultCode == RESULT_OK && requestCode == 10){
        Uri uriSound=data.getData();
        play(this, uriSound);
    }
}

private void play(Context context, Uri uri) {

    try {
        MediaPlayer mp = new MediaPlayer();
        mp.setDataSource(context, uri);
        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();
    }
}

}

2 个答案:

答案 0 :(得分:0)

我认为您忘记为播放按钮实现OnClickListener。

Button play = (Button) this.findViewById(R.id.button2);
play.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        play(this, uriSound);
    }

});

要获得urisound,请将其从onActivityResult中的局部变量转换为类MainActivity的字段

private Uri uriSound;

不要忘记更改onActivityResult

中的代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

   if(resultCode == RESULT_OK && requestCode == 10){
       uriSound=data.getData();
       play(this, uriSound);
   }
}

答案 1 :(得分:0)

问题是你在玩家准备好之前就开始了,看看这个图

https://image.slidesharecdn.com/mediaplayer-110716092828-phpapp02/95/android-media-player-9-728.jpg?cb=1310809360

private void play(Context context, Uri uri) {
    MediaPlayer mp = new MediaPlayer();
    mp.setDataSource(context, uri);
    mp.prepareAsync();
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start();
    }
   });
}}

尝试这样的事情。