当我添加mediaplayer。我希望在我重新打开应用程序时启动音频,但它没有启动它
public MediaPlayer mediaPlayer;
int length = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mediaPlayer = MediaPlayer.create(this, R.raw.andhadhun);
mediaPlayer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mediaPlayer.pause();
length = mediaPlayer.getCurrentPosition();
}
@Override
protected void onResume() {
super.onResume();
mediaPlayer.setOnPreparedListener(MediaPlayer::start);
}
这将工作,它暂停MediaPlayer
在onStop
和恢复在onResume
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this, R.raw.audio);
mediaPlayer.start();
}
@Override
protected void onStop() {
super.onStop();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
@Override
protected void onResume() {
super.onResume();
if (!mediaPlayer.isPlaying() && mediaPlayer != null) {
mediaPlayer.start();
}
}
}
试试这段代码
private MediaPlayer mediaPlayer = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mediaPlayer = MediaPlayer.create(this,R.raw.test);
mediaPlayer.start();
}
@Override
protected void onPause() {
if(mediaPlayer!=null)
mediaPlayer.pause();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if(mediaPlayer!=null) {
mediaPlayer.start();
}
}