Android - 如何让手机随着音乐的播放而振动 [英] Android - How to make the phone vibrate to the music playing

查看:72
本文介绍了Android - 如何让手机随着音乐的播放而振动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 开发的新手.我想做一个本质上是音乐播放器的应用程序,但手机可以随着音乐播放的节拍振动.我记得最早的诺基亚手机有这个功能,我想重新创造这个乐趣.

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 phones had this feature, I want to recreate this for fun.

我的问题:这可以作为 Android 应用吗?如果是这样,一般的方法是什么?我是否必须分析歌曲的声音模式然后改变振动强度?

My question: is this possible as an Android app? If so, what are the general approaches? Do I have to analyse the sound patterns of the song then alter the vibration intensity?

谢谢!

推荐答案

我对这个问题很感兴趣,经过深入研究,我想出了如何去做.那么我们开始吧.

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 中添加的作为第一个参数,我们可以传递歌曲的持续时间,我们可以通过这种方式获得这个持续时间(source):

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

作为第二个参数,我们需要在帮助下创建 AudioAttributesAudioAttributes.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.

附言不要忘记许可:

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

这篇关于Android - 如何让手机随着音乐的播放而振动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆