[英]Why doesn't my song work in my android app?
My audio doesn't play. 我的音频无法播放。 What is the problem ?? 问题是什么 ??
public class AudioActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
final MediaPlayer mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
Button play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
mp.start();
}
});
Button bause = (Button) findViewById(R.id.bause);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
mp.pause();
}
});
}
}
You called setOnClickListener()
on the play button twice. 您在播放按钮上两次调用了setOnClickListener()
。 You meant to call bause.setOnClickListener()
. 您打算调用bause.setOnClickListener()
。 When you hit the play button, instead it is pausing. 当您按下播放按钮时,它正在暂停。
You are setting OnClickListener of play button twice. 您要设置播放按钮的OnClickListener两次。 So when you click the play button it will pause the media player instead of playing it. 因此,当您单击播放按钮时,它将暂停媒体播放器而不是播放它。
change it to following: 将其更改为以下内容:
Button bause = (Button) findViewById(R.id.bause);
bause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
mp.pause();
}
});
This has to do with method scopes. 这与方法范围有关。 You're creating the MediaPlayer
instance inside the onCreate
method. 您正在onCreate
方法中创建MediaPlayer
实例。 When that method ends, the mp
variable goes away as well since it was created in the method's scope. 当该方法结束时, mp
变量也消失了,因为它是在方法的作用域中创建的。 When the onClickListener
is executed, the variable doesn't exist anymore. 当执行onClickListener
,该变量不再存在。 Move the variable declaration to the class' scope, so that it remains available for the lifetime of the class. 将变量声明移到类的作用域,以便在类的生存期内保持可用。 Something like: 就像是:
public class AudioActivity extends AppCompatActivity {
private MediaPlayer mp;
//...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.