Skip to content Skip to sidebar Skip to footer

Android - How To Make The Phone Vibrate To The Music Playing

I am new to Android development. I want to make an app that is essentially a music player but the phone can vibrate to the beat of the music playing. I remember the earliest Nokia

Solution 1:

I got interested with this question and after deep research I figured out how to do that. So here we go.

import android.media.MediaPlayer;
import android.os.Vibrator;

privateVibrator vibrator;
privateMediaPlayer player;
publicvoidonCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    player = MediaPlayer.create(this, R.raw.music);
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    player.start();

    //HERE WE WILL START VIBRATIONButton button = (Button) findViewById(R.id.btn);
    button.setOnClickListener(this);
}

publicvoidonClick(View v){
    player.stop();
    vibrator.cancel();
}

This is general approach for playing music and now work tight with the method vibrate();. From all of constructors of class Vibrator we need this one:

publicvoidvibrate(long milliseconds, AudioAttributes attributes);

It was added in API 21 As first parameter we can pass the duration of the song and this duration we can get this way (source):

StringmediaPath= Uri.parse("android.resource://<your-package-name>/raw/filename").getPath();
MediaMetadataRetrievermmr=newMediaMetadataRetriever();
mmr.setDataSource(mediaPath);
Stringduration= mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);

As second parameter we need to create AudioAttributes with the help of AudioAttributes.Builder:

vibrator.vibrate(duration, new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build());

Please, NOTE: I haven't tried it. But the doc said it should works fine. Let me know if that is completed way. Best regards.

P.S. Don't forget permission:

<uses-permissionandroid:name="android.permission.VIBRATE" />

Post a Comment for "Android - How To Make The Phone Vibrate To The Music Playing"