且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android-如何使手机随着音乐播放而振动

更新时间:2022-01-02 22:58:43

我对这个问题很感兴趣,经过深入研究,我找到了解决方法.所以我们开始吧.

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;

private Vibrator vibrator;
private MediaPlayer player;
public void onCreate(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 VIBRATION

    Button button = (Button) findViewById(R.id.btn);
    button.setOnClickListener(this);
}

public void onClick(View v){
    player.stop();
    vibrator.cancel();
}

这是播放音乐的通用方法,现在可以与 vibrate(); 方法紧密配合.从所有 Vibrator 的构造函数中,我们需要以下一个:>

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:

public void vibrate (long milliseconds, AudioAttributes attributes);

它是在 API 21 中添加的作为第一个参数,我们可以传递歌曲的持续时间,而这个持续时间可以通过这种方式获得(

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):

String mediaPath = Uri.parse("android.resource://<your-package-name>/raw/filename").getPath();
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(mediaPath);
String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);

作为第二个参数,我们需要在帮助下创建 AudioAttributes AudioAttributes.Builder :

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.不要忘记许可:

P.S. Don't forget permission:

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