首页 > 解决方案 > 振动效果很好,但声音在 android 上没有

问题描述

我想同时应用振动和声音。振动工作正常,但声音不起作用。我得到的声音是 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();
    }

}

标签: android

解决方案


这是一种不同的、更短的方法来创建mediaPlayer

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();

所以现在,这就是你的代码应该是什么样子。您不需要tryorcatch块:

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
v.vibrate(2000);

mediaPlayer在开始振动之前尝试启动。如果这不起作用,请确保您已在设备中打开声音。如果仍有问题,请在下面发布新问题。但是,如果您为您的应用程序启用了声音和振动,我不明白为什么它不应该工作。


推荐阅读