手机喊话应用实现思路

手机要是动一下,就喊话“摇摇零线,摇摇零线”,是不是比较酷,

这里实现一下手机翻转一下,播放声音的效果,

通过sensor识别到手机的运动状况,然后播放音频,


public class MainActivity extends AppCompatActivity {
    MySensorEventListener sensorEventListener;
    private String tag = "test9";

    public class MySensorEventListener implements SensorEventListener {

        private float prevY;
        private float prevZ;

        @Override
        public void onSensorChanged(SensorEvent event) {
            float[] values = event.values;
            int type = event.sensor.getType();
            if (type == Sensor.TYPE_ACCELEROMETER) {
                float x = values[0];
                float y = values[1];
                float z = values[2];
                if (Float.compare(prevY, y) != 0 && Float.compare(prevZ, z) != 0) {
                    if (y > prevY && z > prevZ) {
                        // 顺时针翻转
                        Log.i(tag, "1====");
                        onFlip();
                    } else if (y < prevY && z < prevZ) {
                        // 逆时针翻转
                        Log.i(tag, "2====");
                        onFlip();
                        Play();
                    }
                }
            } else if (type == Sensor.TYPE_GYROSCOPE) {
                // 使用陀螺仪传感器的数据识别翻转,具体算法需要自己实现
            }
        }

        private void onFlip() {
            // 执行翻转后的操作
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // Do nothing
        }
    }

    void Play()  {
        MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.hello);
  //      MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            Log.i(tag, "play =========== ");
  //          mediaPlayer.setDataSource("/sdcard/Recordings/910.m4a");
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sensorEventListener = new MySensorEventListener();
        SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(sensorEventListener,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);


    }
}

初步的一个实现,没有使用service,直接播放声音,连续调用会出现同时播放的情况,反而有了回声的效果

你可能感兴趣的:(Android,Input系统,创意,智能手机,android)