我正在尝试在 React Native 中创建一个小应用程序,它执行以下操作:
- 手机摇晃时播放声音;
- 当手机停止震动时停止声音。
目前我有以下处理抖动事件的代码:
进口:
import * as React from 'react';
import {Text, View, Image, Dimensions} from 'react-native';
import {Grid, Col, Row} from 'react-native-easy-grid';
import Sound from 'react-native-sound';
import {accelerometer} from 'react-native-sensors';
import {map, filter} from 'rxjs/operators';
我正在使用一个包含以下方法的类组件:
constructor(props) {
super(props);
Sound.setCategory('Playback');
this.mnezo = new Sound('mnezo.mp3', Sound.MAIN_BUNDLE, err => {
if (err) {
console.log('Failed to load sound.', err);
return;
}
console.log('sound duration:' + this.mnezo.getDuration());
});
this.state = {
accelerometerData: {},
isPlaying: false,
};
}
componentDidMount() {
this.__subscribe();
}
componentWillUnmount() {
this.__unsubscribe();
}
__subscribe = () => {
const SHAKE_THRESHOLD = 26;
const MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
this.lastShakeTime = 0;
this.accelerometerSubscription = accelerometer
.pipe(
map(
({x, y, z}) =>
Math.sqrt(
Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2),
) /* - SensorManager.GRAVITY_EARTH */,
),
filter(acceleration => acceleration > SHAKE_THRESHOLD),
)
.subscribe(acceleration => {
const curTime = new Date().getTime();
console.log(acceleration < 30);
if (acceleration < 30) {
this.mnezo.stop();
this.setState({isPlaying: false});
}
if (acceleration > 30) {
if (!this.state.isPlaying) {
this.mnezo.play(success => {
if (success) {
console.log('palying.');
} else {
console.log('play failed.');
}
});
}
this.setState({isPlaying: true});
}
if (curTime - this.lastShakeTime > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
this.lastShakeTime = curTime;
console.log('Shaken device! acceleration: ', acceleration);
}
});
};
__unsubscribe = () => {
this._subscription && this._subscription.remove();
this._subscription = null;
};
我正在尝试检测加速度是否超过值以启动和停止声音。然而,当震动方向改变时(例如,从向上到向下),加速度值会直线下降,几乎在声音开始播放时就停止了。
有什么建议可以解决这个问题吗?我是否正确解决了这个问题,还是应该寻找不同的替代方案?
我也尝试过 react-native-shake-event 和 react-native-shake,但我无法停止声音。
我还必须提到,我才刚刚开始学习 React Native。