gpt4 book ai didi

java - 停止MediaPlayer的问题

转载 作者:行者123 更新时间:2023-12-03 01:55:18 25 4
gpt4 key购买 nike

我的应用程序包含一个mediaplayer,它在audio.xml中带有一个(播放/暂停)按钮,但是问题是我无法找到正确的代码来在页面被破坏之前停止MediaPlayer,并且因为该应用程序在我登录时崩溃音频页面(xml)并在不运行mediaplayer的情况下退出,这是我使用的代码:

 public class audio extends Langue implements Runnable,

OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
// private Button stopMedia;
private MediaPlayer mp;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
//stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
//stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);


}

public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();

while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}

public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.espoir);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("Play");
} else {
mp.start();
startMedia.setText("Pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}

/* if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("Play");
seekBar.setProgress(0);
}
}
*/
}

public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);

}
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;

}
return super.onOptionsItemSelected(item);
}
// stop song
@Override
protected void onPause(){
super.onPause();
mp.stop();
finish();
}


}

最佳答案

在onPause()方法中执行类似的操作以防止崩溃

try{
mp.stop();
} catch(Exception e) {
}

finish();

关于java - 停止MediaPlayer的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36138258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com