如何在按钮上播放声音

时间:2015-04-16 04:00:30

标签: java android audio

我的新手这是我的代码 声音不播放但是当我点击按钮时,吐司就会显示出来 有人帮我吗?

public class DB_Parse extends Activity {

MediaPlayer mp;
Button button;
int ,sound;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.keterangan);


    final int sound = iIdentifikasi.getIntExtra("dataID", 0);

    button=(Button)findViewById(R.id.btnsound);

        button.setOnClickListener(new OnClickListener() {

        @Override    
        public void onClick(View v) {
            if (sound==1){
                mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
                mp.start();

            }

                     Toast.makeText(getApplicationContext(), 
                                   "Sound is Play", Toast.LENGTH_LONG).show();
            }

});

}

}

if(sound == 1)1来自sqlite中的_id

3 个答案:

答案 0 :(得分:1)

尝试这种方式它将起作用

  public class DB_Parse extends Activity {

private static final String TAG = "MyActivity";

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

    Log.v(TAG, "Initializing sounds...");

    final MediaPlayer mp = MediaPlayer.create(this, R.raw.youraudio);

    Button play_button = (Button)this.findViewById(R.id.play_button);
    play_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v(TAG, "Playing sound...");
            mp.start();
        }
    });
    Log.v(TAG, "Sounds initialized.");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

答案 1 :(得分:1)

将您的音频/媒体文件放入资源文件夹,而不是放入原始文件夹,并按照上面的代码段,它对我来说工作得很好..

try
{
   AssetFileDescriptor afd = getAssets().openFd("your_media_file_name.mp3");
   MediaPlayer mp = new MediaPlayer();
   mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
   mp.prepare();
   mp.start();
}
catch(Exception e)
{ e.printStackTrace();}

点击你的按钮点击事件

答案 2 :(得分:-1)

首先,您要声明两次变量声音。 请改变:

 final int sound = iIdentifikasi.getIntExtra("dataID", 0);

 sound = iIdentifikasi.getIntExtra("dataID", 0);

你应该尝试的另一件事是改变if中的吐司,所以你确定声音是1.

       if (sound==1){
            mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
            mp.start();

            Toast.makeText(getApplicationContext(), 
                               "Sound is Play", Toast.LENGTH_LONG).show();

        }

如果toast没有显示你的int声音不是1.