当前代码:
MediaPlayer mp;
button1=(ImageButton)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Activity1.class);
startActivity(i);
}
});
那么按钮如何开始新的活动并播放声音呢?
我尝试过的方法:各种方法,如playSound();在方法中。
它只播放默认的Android声音。我想要一个存储在原始目录中的特定声音。因此,当按下按钮时,它会启动启动活动的意图以及特定的声音。
错误:
当我尝试放入MediaPlayer时;在按钮上方,它表示已经定义了变量mp。我只需要有人附加活动启动代码,这样它也会播放声音。
答案 0 :(得分:0)
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), Uri.parse(""));
mp.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer player) {
// TODO Auto-generated method stub
player.start();
Intent i = new Intent(getApplicationContext(), Activity1.class);
startActivity(i);
}
});
答案 1 :(得分:0)
首先,您需要将sound.mp3放入原始文件夹中 MediaPlayer mp;
button1=(ImageButton)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mp = MediaPlayer.create(Music.this, R.raw.sound);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mp.start();
Intent i = new Intent(getApplicationContext(), Activity1.class);
startActivity(i);
}
});
答案 2 :(得分:0)
别忘了发布它:http://developer.android.com/reference/android/media/MediaPlayer.html#release%28%29
Mediaplayer mediaPlayer = MediaPlayer.create(this, R.raw.YOURMP3NAMEFILE);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if(mp != null){
mp.release();
mediaPlayer = null;
Log.d(TAG, "release mediaplayer");
}
}
});
mediaPlayer.start();
launchSecondActivity();