我想同时施加振动和声音。
振动效果很好,但声音不起作用。
我正在将声音作为mp3。
我该如何解决这个问题?
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
// Initializing instance of Vibrator.
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Initializing instance of MediaPlayer.
MediaPlayer mediaPlayer = new MediaPlayer();
// Starting Vibration
v.vibrate(2000);
try {
// Setting the source of audio file.
//String path = "android.resource://"+"com.example.myproject"+"/raw/"+audioFile;
mediaPlayer.setDataSource(context,Uri.parse("android.resource://"+"com.example.fahad.finalyearprojectlayout"+"/raw/"+"sound.mp3")); // Fill the information accordingly.
mediaPlayer.prepare();
// playing audio.
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
最佳答案
这是创建mediaPlayer
的另一种较短的方法:
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
所以现在,这就是您的代码的外观。您不需要
try
或catch
块:MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
v.vibrate(2000);
开始振动之前,请尝试启动
mediaPlayer
。如果这不起作用,请确保已在设备中打开声音。如果仍有问题,请在下面发布新问题。但是,如果您为应用程序启用了声音和振动功能,则我看不到为什么它不起作用。