java如何在Android中使用声音和吐司
我想在我的安卓应用程序中弹出我的吐司时播放一个声音
以下是我在主课上的祝酒词代码:
private void workEndNotification() {
//Custom Toast notification for the Work End Reminder.
LayoutInflater inflaterWork = getLayoutInflater();
View toastLayout = inflaterWork.inflate(R.layout.work_notification_toast, (ViewGroup) findViewById(R.id.toast_root_view));
TextView header = (TextView) toastLayout.findViewById(R.id.toast_header);
header.setText("Work Day Over Soon!");
final Toast toastWork = new Toast(getApplicationContext());
toastWork.setGravity(Gravity.CENTER, 0, 0);
toastWork.setDuration(Toast.LENGTH_SHORT);
toastWork.setView(toastLayout);
toastWork.show();
myHandler.postDelayed(new Runnable() {
public void run() {
toastWork.cancel();
}
}, 1);
};
以下是我的SoundPool类(http://www.vogella.com/tutorials/AndroidMedia/article.html)中的声音代码:
class PlaySound extends Activity implements OnTouchListener {
private SoundPool soundPool;
private int soundID;
boolean loaded = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.work_notification_toast);
View view = findViewById(R.id.toast_header);
view.setOnTouchListener(this);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.sound1, 1);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}
return false;
}
}
我知道我不是在toast方法中调用它,我知道我使用的是touchview。我怎样才能使声音只在祝酒词出现的同时才出现呢。我一直在努力,但没有成功
我不想碰一下什么的。只是为了让它简单地玩祝酒词
# 1 楼答案
做一个这样的函数
并在显示
Toast
的地方这样称呼它您还需要替换资源,使其与您的匹配
编辑:您似乎想播放几种声音。你可以自己制作一个简单的声音池
制作一个你想这样玩的int数组或资源,当
MediaPlayer
玩完后,告诉他玩下一个,直到它玩完数组中的最后一个