声音如何振动

时间:2018-11-21 04:59:56

标签: java android

我想在振动的同时添加声音。

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
    Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(2000);
}

振动已成功应用,但是如何在手机振动时添加声音?

1 个答案:

答案 0 :(得分:1)

您可以使用MediaPlayer轻松地做到这一点。

首先,创建MediaPlayer类的实例:

MediaPlayer mediaPlayer = new MediaPlayer();

然后,为此设置源文件,首先将音频文件放置在res/raw目录的Project文件夹中,然后使用以下代码:

mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}");

然后使用以下代码播放该文件:

mediaPlayer.prepare();
mediaPlayer.start();

请记住,您必须将此代码放在try | catch块中。

现在您的整个代码将是这样:

@Override
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.
        mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}");  // Fill the information accordingly.
        mediaPlayer.prepare();

        // playing audio.
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}