我有一个具有所需功能的应用程序。
Howerver,在某些时候会显示祝酒词,我希望在显示祝酒词的同时播放双哔声,以提醒用户显示正在显示的消息。
我不确定在Android中播放声音的最佳方法是什么,或者是否有一些我可以访问用于警报的默认声音。
非常感谢一些指导!
由于
更新
我的主要活动文件中有以下代码:
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
有什么想法吗?
答案 0 :(得分:5)
您可以将音频文件放在项目的 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());
}
答案 1 :(得分:2)
使用MediaPlayer
,
http://developer.android.com/reference/android/media/MediaPlayer.html
有很多关于如何使用的知识,这在上面的链接中有所介绍。这是一个衬衫片段,说明了用法,
final MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(...);
mediaPlayer.prepare();
} catch (IllegalStateException e) {
mediaPlayer.release();
} catch (IOException e) {
mediaPlayer.release();
} catch (IllegalArgumentException e) {
mediaPlayer.release();
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
}
});
mediaPlayer.start();
答案 2 :(得分:1)
try {
AssetFileDescriptor afd = getAssets().openFd("gavel_single.wav");
mMediaplayer = new MediaPlayer();
mMediaplayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mMediaplayer.prepare();
mMediaplayer.start();
mMediaplayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mMediaPlayer) {
mMediaPlayer.stop();
mMediaPlayer.release();
}
});
} catch (Exception e) {
e.printStackTrace();
}
将您的音乐文件放入资产文件夹