in react-native how to use body-pix - javascript

import { Camera, CameraType } from 'expo-camera';
import React, { useRef } from "react";
// import logo from './logo.svg';
import * as tf from "#tensorflow/tfjs";
import * as bodyPix from "#tensorflow-models/body-pix";
import { useState } from 'react';
import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
//AFTER IMPORT
export default function App() {
const [type, setType] = useState(CameraType.back);
const [permission, requestPermission] = Camera.useCameraPermissions();
const canvasRef = useRef(null);
//next part
const runBodysegment = async () => {
const net = await bodyPix.load();
console.log("BodyPix model loaded.");
// Loop and detect hands
setInterval(() => {
detect(net);
}, 100)
};
//next part
const detect = async (net) => {
const person = await net.segmentPersonParts(video);
console.log(person);
const coloredPartImage = bodyPix.toColoredPartMask(person);
bodyPix.drawMask(
canvasRef.current,
video,
coloredPartImage,
0.7,
0,
false
);
runBodysegment();
if (!permission) {
// Camera permissions are still loading
return <View />;
}
if (!permission.granted) {
// Camera permissions are not granted yet
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center' }}>We need your permission to show the camera</Text>
<Button onPress={requestPermission} title="grant permission" />
</View>
);
}
function toggleCameraType() {
setType(current => (current === CameraType.back ? CameraType.front : CameraType.back));
}
return (
<View style={styles.container}>
<Camera style={styles.camera} type={type}>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={toggleCameraType}>
<Text style={styles.text}>Flip Camera</Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
//next part
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
camera: {
flex: 1,
},
buttonContainer: {
flex: 1,
flexDirection: 'row',
backgroundColor: 'transparent',
margin: 64,
},
button: {
flex: 1,
alignSelf: 'flex-end',
alignItems: 'center',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'white',
},
});
};
I want to use body-pix in my react-native app for android .
can any one help me how to do it .
I want my app to open a camera and in my camera there will be a body body-pix working
in my android app
I want my react-native app to work properly with body-pix
I had try it many time time but I can't do it properly

Related

How to customise Webview to navigate website using back button in React Native and exit app by pressing back twice?

I am facing issues in implementing Webview navigation of website using back button as back button when pressed exits the app.
I implemented a button functionality that uses the browser functionality of going back to the previous page and next page. But, this was not an effective implementation.
Here's my webview code:
import React, { useEffect, useState, useRef } from "react";
import {
View,
Text,
StyleSheet,
SafeAreaView,
StatusBar,
Alert,
BackHandler,
} from "react-native";
import { State, TouchableOpacity } from "react-native-gesture-handler";
import * as firebase from "firebase";
import { loggingOut } from "../API/firebaseMethods";
import { WebView } from "react-native-webview";
import { createBottomTabNavigator } from "#react-navigation/bottom-tabs";
import SignIn from "./SignIn";
import SignUp from "./SignUp";
import { useBackHandler } from "#react-native-community/hooks";
import NavigationView from "./NavigationView";
const Tab = createBottomTabNavigator();
const LENNY = "https://www.testbooking.lennyconsulting.com/";
const THEME_COLOR = "#000000";
export default function Dashboard({ navigation }) {
function backActionHandler() {
Alert.alert("", "Are Your Sure To Exit The App?", [
{
text: "No",
onPress: () => null,
style: "cancel",
},
{
text: "Yes",
onPress: () => BackHandler.exitApp(),
},
]);
return true;
}
useBackHandler(backActionHandler);
let currentUserUID = firebase.auth().currentUser.uid;
const [firstName, setFirstName] = useState("");
useEffect(() => {
async function getUserInfo() {
try {
let doc = await firebase
.firestore()
.collection("users")
.doc(currentUserUID)
.get();
if (!doc.exists) {
Alert.alert("No user data found!");
} else {
let dataObj = doc.data();
setFirstName(dataObj.firstName);
}
} catch (err) {
Alert.alert("There is an error.", err.message);
}
}
getUserInfo();
});
const handlePress = () => {
loggingOut();
navigation.replace("Home");
};
const AppStatusBar = ({ backgroundColor, ...props }) => {
return (
<View style={[styles.statusBar, backgroundColor]}>
<StatusBar backgroundColor={backgroundColor} {...props} />
</View>
);
};
const BAR_HEIGHT = StatusBar.currentHeight;
const styles = StyleSheet.create({
statusBar: {
height: BAR_HEIGHT,
},
});
const webViewRef = useRef();
const [canGoBack, setCanGoBack] = useState(false);
const [canGoForward, setCanGoForward] = useState(false);
const handleBackPress = () => {
webViewRef.current.goBack();
};
const handleForwardPress = () => {
webViewRef.current.goForward();
};
return (
<SafeAreaView style={styles.container}>
<SafeAreaView style={{ width: "100%", height: "100%" }}>
<WebView
ref={webViewRef}
source={{ uri: LENNY }}
onLoad={console.log("Loaded")}
onNavigationStateChange={(state) => {
const back = state.canGoBack;
const forward = state.canGoForward;
setCanGoBack(back);
setCanGoForward(forward);
}}
/>
<NavigationView
onBackPress={handleBackPress}
onForwardPress={handleForwardPress}
canGoBack={canGoBack}
canGoForward={canGoForward}
/>
<StatusBar style="auto" />
<View>
<Text style={styles.text}>Hi {firstName}</Text>
<TouchableOpacity style={styles.button} onPress={handlePress}>
<Text style={styles.buttonText}>Log Out</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
<SafeAreaView style={styles.topSafeArea} />
<SafeAreaView style={styles.bottomSafeArea}>
<AppStatusBar backgroundColor={THEME_COLOR} barStyle="light-content" />
</SafeAreaView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
topSafeArea: {
flex: 1,
backgroundColor: THEME_COLOR,
},
bottomSafeArea: {
flex: 1,
backgroundColor: THEME_COLOR,
},
button: {
width: 150,
padding: 5,
backgroundColor: "#ff9999",
borderWidth: 2,
borderColor: "white",
borderRadius: 15,
alignSelf: "center",
},
buttonText: {
fontSize: 20,
color: "white",
fontWeight: "bold",
textAlign: "center",
},
container: {
height: "100%",
width: "100%",
backgroundColor: "#3FC5AB",
alignItems: "center",
justifyContent: "center",
},
text: {
textAlign: "center",
fontSize: 20,
fontStyle: "italic",
marginTop: "2%",
marginBottom: "10%",
fontWeight: "bold",
color: "black",
},
titleText: {
textAlign: "center",
fontSize: 30,
fontWeight: "bold",
color: "#2E6194",
},
});
Please someone help me. I am new to React Native.

React Native module fails to load because of a single function that is not even invoked. Error : 'AppRegistry.registerComponent'

So I'm having some bundling problem with a single function that is not even invoked. const { status } = await BarCodeScanner.requestPermissionsAsync(); The function should be invoked when the QR code is scanned and the string information gets parsed and saved to a SQLite database. There is something wrong with bundling the app. I tried to set a setTimeOut at the root but to no avail. Here is the error That I'm getting:
ERROR TypeError: undefined is not an object (evaluating '_Splash.default.TABLE_REFERENCE')
LOG Running "main" with {"rootTag":91,"initialProps":{}}
ERROR Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.
Here is the actual screen. nothing fancy really.
import { StackScreenProps } from "#react-navigation/stack";
import { BarCodeScanner, BarCodeScannerResult } from "expo-barcode-scanner";
import AsyncStorage from "#react-native-async-storage/async-storage";
import React, { useEffect, useState } from "react";
import {
Alert,
StyleSheet,
Text,
useWindowDimensions,
View,
ScrollView,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { BackBar } from "../../components/BackBar";
import { useDispatch } from "react-redux";
import {
IntroScreen,
IntroStackParamList,
} from "../../navigation/intro/StackUtil";
import { EnumFonts } from "../../types/enums/fonts.enum";
import addSplashUriToDatabase from "../../database/addSplashUriToDatabase";
import { setStarter } from "../../store/starter/actions";
import { Camera } from "expo-camera";
interface Props
extends StackScreenProps<IntroStackParamList, IntroScreen.ScanQR> {}
const ScanQRScreen: React.FC<Props> = (props) => {
const [hasPermissions, setHasPermissions] = useState(false);
const [scanned, setScanned] = useState(false);
const [processing, setProcessing] = useState(false);
const { width, height } = useWindowDimensions();
const dispatch = useDispatch();
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermissions(status === "granted");
})();
}, []);
const handleBarCodeScanned = async ({ type, data }: BarCodeScannerResult) => {
setScanned(true);
console.log(
`Bar code with type ${type} and data ${data} has been scanned!`
);
try {
const success = await addSplashUriToDatabase(data);
if (success) {
// Navigate to other screen
dispatch(setStarter(false));
try {
const value = await AsyncStorage.setItem("#starter", "true");
if (value !== null) {
// value previously stored
// setStarter("false");
}
} catch (e) {
// error reading value
}
}
} catch (error) {
console.error(error);
Alert.alert(
"Fail to scan QR code",
"Please let us know, this could caused by invalid participant names.",
[
{
text: "OK",
},
// {text: 'Report Bug', onPress: failOnScan},
],
{ cancelable: true }
);
}
};
return (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView style={{ flex: 1, padding: "5%" }}>
<BackBar goBackFunction={props.navigation.goBack} />
<View
style={{ flex: 0.3, justifyContent: "space-evenly", marginTop: 30 }}
>
<Text
style={{
fontFamily: EnumFonts.BOLD,
fontSize: 30,
marginVertical: 10,
}}
>
Scan a Splash code
</Text>
<Text
style={{
fontFamily: EnumFonts.REGULAR,
fontSize: 20,
marginVertical: 10,
}}
>
Line up the Splash code in the red square. Ensure the other phone
has its screen brightness at maximum setting.
</Text>
</View>
<View style={{ flex: 0.6, justifyContent: "space-around" }}>
{hasPermissions && (
<>
<View
style={{
width: width * 0.8,
borderWidth: 5,
borderColor: scanned ? "green" : "red",
backgroundColor: "black",
alignSelf: "center",
}}
>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{
width: "100%",
height: height * 0.45,
borderWidth: 1,
borderColor: "red",
}}
/>
</View>
<Text
style={{
fontFamily: EnumFonts.REGULAR,
fontSize: 18,
textAlign: "center",
marginTop: 15,
}}
>
The square will turn green to indicate a successful scan
position
</Text>
</>
)}
{!hasPermissions && (
<Text
style={{
fontFamily: EnumFonts.MEDIUM,
fontSize: 20,
textAlign: "justify",
}}
>
Please allow us to use camera to scan qr
</Text>
)}
</View>
</ScrollView>
</SafeAreaView>
);
};
export default ScanQRScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});

React Native Expo: Barcodescanner camera doesn't rotate when i press the rotate button

I'm using React Native Expo. Currently i'm trying to make an application which uses a barcodescanner for scanning QR-code objects. I've implemented a turn camera button for the front or back camera but when i press the button it does nothing only when i switch from one screen to the other. I think there is something wrong with refreshing the screen immediately but i've no clue of how i should solve this problem
Code:
import React, { useEffect, useState, useLayoutEffect } from 'react';
import { StyleSheet, Text, View, Button, Alert, ActivityIndicator, Pressable } from 'react-native';
import { globalStyles } from '../styles/global';
// import { Camera, BarCodeScanningResult } from 'expo-camera';
import { BarCodeScanner } from 'expo-barcode-scanner';
import BarcodeMask from 'react-native-barcode-mask';
import { useIsFocused, useNavigation } from '#react-navigation/native';
import CustomButton from '../components/CustomButton';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
export function ShowLoading(){
return(
<View style={styles.loader}><ActivityIndicator size="large" color='white'/></View>
)
}
export default function Scan(){
const navigation = useNavigation()
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const [loading, setLoading] = useState(false);
const [type, setType] = useState(BarCodeScanner.Constants.Type.back);
const isFocused = useIsFocused()
useEffect(() => {
(async () => {
const {status} = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
// useEffect(() => {
// if(loading){
// setLoading(true)
// } else {
// setLoading(false)
// }
// },[loading])
const initScanner = async() => {
const {status} = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
}
const handleNavigation = async() => {
setScanned(false)
navigation.navigate('Oefening')
}
const handleNo = () => {
setScanned(false)
}
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true)
setLoading(true)
setTimeout(() => { Alert.alert(
'QR-Code gevonden',
`QR-Code met type ${type} en data ${data} is gescand, wilt u verder gaan?`,
[
{
text: "Nee",
onPress: () => handleNo(),
},
{
text: "Ja",
onPress: () => handleNavigation(),
}
]
), setLoading(false)}, 1000)
}
if (hasPermission === null) {
return <View style={styles.permissionWrapper}>
<Text style={styles.permissionText}>Een moment geduld..</Text>
<ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator>
</View>;
}
if (hasPermission === false) {
return <Text>Geen toegang tot uw camera!</Text>;
}
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-end'}}>
{loading? (<View style={styles.loader}><ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator></View>
) : (
isFocused &&
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
type={type}
>
<View style={styles.topOptions}>
<View style={styles.cameraRotateWrapper}>
<Pressable style={styles.cameraRotate}
onPress={() => {
setType(
type === BarCodeScanner.Constants.Type.back
? BarCodeScanner.Constants.Type.front
: BarCodeScanner.Constants.Type.back
);
}}
>
<Icon name='rotate-3d-variant' size={40} color={'white'}></Icon>
</Pressable>
</View>
</View>
<BarcodeMask edgeColor={'#62B1F6'} showAnimatedLine={true}/>
</BarCodeScanner>)}
{scanned? <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Gevonden!</Text></View> : <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Zoeken naar QR-Code.... </Text></View>}
{/* {scanned? <Button title={'Opnieuw scannen'} onPress={() => setScanned(false)} /> : null} */}
<View style={styles.bottomOptions}>
<CustomButton textValue="Herladen" onPress={initScanner}></CustomButton>
</View>
</View>
)
}
const styles = StyleSheet.create({
loader: {
justifyContent: "center",
alignItems: 'center',
},
permissionWrapper: {
justifyContent: 'center',
alignItems:'center',
margin: 15,
},
permissionText: {
fontSize: 16,
fontWeight: 'bold',
},
topOptions: {
marginTop: 20,
justifyContent: 'space-between',
marginHorizontal: '10%'
},
searchTextWrapper: {
},
searchText: {
color: 'white',
fontSize: 18,
textAlign: 'center',
},
cameraRotateWrapper: {
width: 50,
height: 50,
},
cameraRotate: {
justifyContent: 'center',
alignItems: 'center',
borderWidth: 1,
borderColor: "white",
backgroundColor: '#1f69b1',
borderRadius: 10,
},
bottomOptions: {
marginHorizontal: '10%',
marginBottom: 10,
},
})

Strange borders on production build in react native, but not in develope mode

In my App I have a screen that normally looks like this
but when I build for production the title wrapper gets pushed down a few pixels, which results in some strange formatting:
I don't really understand why the app looks different when build for release vs when I develop it.
I also tested it on multiple devices but I have the same error on all of them.
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import BottomBar from './component/BottomBar';
export default function ScanScreen({ navigation }) {
const [hasPermission, setHasPermission] = useState(null);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
navigation.navigate("Shelf", { shelfID: data.toString() })
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
<View style={styles.contentContainer}>
<View style={styles.titleWrapper}>
<Text style={styles.text}> Shelf Scanner </Text>
</View>
<View style={{flex: 1}}>
<BarCodeScanner
onBarCodeScanned={handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
</View>
</View>
<BottomBar navigation={navigation} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
flexDirection: 'row',
},
titleWrapper: {
width: '100%',
top: 30,
height: 50,
alignSelf: 'center',
alignItems: 'center',
backgroundColor: '#A2F5AA',
},
text: {
fontSize: 15,
justifyContent: 'center',
fontWeight: 'bold',
flex: 1,
marginTop: 10,
},
contentContainer: {
flex: 1
},
});
I fixed it by removing top: 30, from titleWrapper. The title is now offset in develop mode, but it at least looks correct in the production build

React Native: Why is Expo-AV not playing audio?

I'm attempting to build an app that acts as a soundboard and can play different sounds when different buttons are pressed. I expected the audio to play but instead, I got an error that stated:
Possible Unhandled Promise Rejection (id: 1): TypeError: undefined is not an object (evaluating '_expoAv.Audio.sound.createAsync')
playSound$
This is my code:
import { StatusBar } from "expo-status-bar";
import React, { useState, useEffect } from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
import { Feather } from "#expo/vector-icons";
import { Audio } from "expo-av";
// project made in yarn
// yarn start
// yarn add
export default function App() {
const [sound, setSound] = useState("");
const playSound = async () => {
console.log("Loading Sound");
const { sound } = await Audio.sound.createAsync(
require("./assets/Ayo.mp3")
);
setSound(sound);
console.log("playing sound");
await sound.playAsync();
};
useEffect(() => {
return sound
? () => {
console.log("unloading the sound");
sound.unloadAsync();
}
: undefined;
}, [sound]);
// run useEffect whenever sound state changes
return (
<View style={styles.container}>
<Text>SoundGround</Text>
<View style={{ flexDirection: "row" }}>
<TouchableOpacity onPress={playSound}>
<Feather name="arrow-left" style={styles.iconStyle} />
</TouchableOpacity>
<TouchableOpacity onPress={playSound}>
<Feather name="arrow-right" style={styles.iconStyle} />
</TouchableOpacity>
</View>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
iconStyle: {
fontSize: 100,
},
});
So far, I've tried adding a try/catch block, using different audio formats. I think the error has to do with state not being assigned before it is used to play something - but I'm not sure.
You can implement useRef instead of useState to stop re-rendering!
This worked for me very well.
import { StatusBar } from "expo-status-bar";
import React, { useEffect } from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
import { Feather } from "#expo/vector-icons";
import { Audio } from "expo-av";
// project made in yarn
// yarn start
// yarn add
export default function App() {
const sound = useRef(new Audio.Sound());
useEffect(() => {
return () => sound.current.unloadAsync();
}, []);
const playSound = async () => {
console.log("Loading Sound");
await sound.current.createAsync(require("./assets/Ayo.mp3"));
console.log("playing sound");
const checkLoaded = await sound.current.getStatusAsync();
if (checkLoaded.isLoaded === true) {
console.log("Error in Loading mp3");
} else {
await sound.current.playAsync();
}
};
return (
<View style={styles.container}>
<Text>SoundGround</Text>
<View style={{ flexDirection: "row" }}>
<TouchableOpacity onPress={() => playSound()}>
<Feather name="arrow-left" style={styles.iconStyle} />
</TouchableOpacity>
<TouchableOpacity onPress={() => playSound()}>
<Feather name="arrow-right" style={styles.iconStyle} />
</TouchableOpacity>
</View>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
iconStyle: {
fontSize: 100,
},
});

Categories