Android 声音不能播放
我创建了一个简单的项目,其中一个布局包含两个按钮,下面是我的代码:Android 声音不能播放,android,audio-player,Android,Audio Player,我创建了一个简单的项目,其中一个布局包含两个按钮,下面是我的代码: package com.example.tessound; import android.media.MediaPlayer; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; im
package com.example.tessound;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener
{
MediaPlayer player;
Button play,mute;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.button1);
play.setOnClickListener(this);
mute = (Button)findViewById(R.id.button2);
mute.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View view)
{
if(view.getId()==R.id.button1)
{
playSound(1);
}
else if(view.getId()==R.id.button2)
{
playSound(2);
}
}
public void playSound(int arg)
{
if (arg == 1)
{
player = MediaPlayer.create(this, R.raw.atur);
}
else if (arg == 2)
{
player = MediaPlayer.create(this, R.raw.back);
}
if(player != null)
{
player.setLooping(false);
player.start();
}
try
{
if(player != null)
{
if (player.isPlaying())
{
player.stop();
player.release();
}
}
}
catch(Exception e)
{
}
}
}
当我尝试单击按钮时,声音无法播放。使用日志跟踪控件并查找错误
Log.e("AnyTAG","Description of the Log");
你的代码看起来不错 遵循参数值为1的playSound方法的逻辑: 1) arg==1,因此:
player = MediaPlayer.create(this, R.raw.atur);
2) 播放器已设置为不为空,因此:
player.setLooping(false);
player.start();
3) 那就是你的试块了。玩家不为空且正在玩,因此:
player.stop();
player.release();
所以我认为你是在开始播放,然后立即停止播放。我认为只有当方法没有收到有效参数时,才应该执行try/catch代码,即它应该是前面“if”语句的“else”
编辑:
再看一遍,我认为try/catch代码应该放在方法的顶部。然后,它将停止播放器并将其释放(如果正在使用),然后再尝试播放新声音。从逻辑上讲,这是有道理的。这似乎是正确的答案。我也会使用
SoundPool
而不是MediaPlayer
personalis,所以我应该放player.stop();player.release();在else声明中?我已经建立了另一个项目,几周前我使用了这个代码,没有问题,但我不记得什么时候声音不再播放了,直到现在。。似乎是正确的答案。还有一种可能性是,由于某种原因,资源已损坏,并且播放器在初始化时为空。例如,如果播放器为空,我会添加代码来捕获和警告Toast。(查看这里的MediaPlayer参考:,int))我已经将try/catch移到了方法的顶部,这正在工作:D我的原始文件夹包含atur.mp3、back.mp3、belajar.mp3、level.mp3、skip.mp3、start.mp3。。。当我单击按钮静音时,会播放back.mp3,但当我单击按钮播放时,原始文件夹中的所有mp3都会播放x_x,你知道为什么吗?这只是跟踪logCat中控件的代码!将其粘贴到任何地方,您将在logCat中获得输出!这是用来调试的!我建议您阅读本教程,它涵盖了“日志”和您的声音教程!