gpt4 book ai didi

android - 在 Android 应用程序中实现蜂鸣声

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:26 25 4
gpt4 key购买 nike

我有一个具有所需功能的应用程序。

但是,在某些时候会显示 toast ,我希望在显示 toast 的同时播放两声哔哔声,以提醒用户正在显示的消息。

我不确定在 android 中播放声音的最佳方法是什么,或者是否有一些我可以访问以用于警报的默认声音。

更新

我的主要 Activity 文件中有以下代码:

  public void playAlertTone(final Context context){
Thread t = new Thread(){
public void run(){
MediaPlayer player = null;
int countBeep = 0;
while(countBeep<2){
player = MediaPlayer.create(context,R.raw.beep);
player.start();
countBeep+=1;
try {


Thread.sleep(player.getDuration()+100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();

}

我在 res/raw 中有一个名为 beep 的声音文件

如何在显示 toast 的 if 语句中调用此方法,以便 2 同时发生?

更新 2:

这是我尝试调用警报方法的代码:

  if (elapsedTime > hourAlert)
{
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("HOUR PASSED");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 160);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
playAlertTone(getApplicationContext()); // Edited here now call

最佳答案

您可以将您的音频文件放在项目的res/raw 文件夹中

并在线程中播放音频

public  void playAlertTone(final Context context){


Thread t = new Thread(){
public void run(){
MediaPlayer player = null;
int countBeep = 0;
while(countBeep<2){
player = MediaPlayer.create(context,R.raw.beep);
player.start();
countBeep+=1;
try {

// 100 milisecond is duration gap between two beep
Thread.sleep(player.getDuration()+100);
player.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}
};

t.start();

}

//call it like this from your activity' any method



if(myCondition){

Toast.makeText(getApplicationContext(), text, duration).show();

playAlertTone(getApplicationContext());


}

关于android - 在 Android 应用程序中实现蜂鸣声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10044575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com