I am using react native webrtc but i am getting error of Could not add sender - react-native

// I am getting error of "Could not add sender" after using the getTracks and can i use ontrack and onicecandidate in react native webrtc.
const createOffer = async () => {
try {
peerConnection = new RTCPeerConnection(server);
myremotevideo = new MediaStream();
localstream.getTracks().map(tracks => {
peerConnection.addTrack(tracks, localstream);
tracks.stop()
});
// peerConnection.ontrack = event => {
// event.stram[0].getTracks().forEach(track => {
// myremotevideo.addTrack(track);
// });
// };
// peerConnection.onicecandidate = async event => {
// if (event.candidate) {
// console.log('candiatemay', event.candidate);
// }
// };
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
console.log('myoffer', offer);
} catch (error) {
console.error('err', error);
}
};

Related

React native Expo how to keep tcp socket alive on background

I have a tcp socket client connection and server in my app. My main goal is taking data from server and send it to client connection. It works great while my app is running but if i get app to background it just sends one data and sends other datas after opening app again. I tried expo-task-manager but it just sends first data and doesnt sends after it as before. I was using my function inside useEffect in a context component. My function with task manager is below.
const BACKGROUND_CLIENT_TASK = "background-client-task";
TaskManager.defineTask(BACKGROUND_CLIENT_TASK, async () => {
const now = Date.now();
console.log(
`Got background fetch call at date: ${new Date(now).toISOString()}`
);
const mainFunction = async () => {
const server = TcpSocket.createServer(function (socket) {
socket.on("data", (takenData) => {
const jsonStringData = String.fromCharCode(...takenData);
const data = JSON.parse(jsonStringData);
const clientOptions = {
port: 1500,
host: "localhost",
};
const dataToClientArray = [
`DataProcess1${data}`,
`DataProcess2${data}`,
`DataProcess3${data}`,
];
dataToClientArray.forEach((dataToClient, index) => {
setTimeout(() => {
const client = TcpSocket.createConnection(
clientOptions,
() => {
// Write on the socket
client.write(`${dataToClient}`, "hex");
console.log("client started");
console.log(dataToClient);
// Close socket
client.destroy();
}
);
client.on("data", (data) => {
console.log("Received: ", data.toString());
});
client.on("error", (error) => {
console.log("Error: ", error);
});
client.on("close", () => {
console.log("Connection closed");
});
}, 300 * index);
});
});
socket.on("error", (error) => {
console.log("An error ocurred with client socket ", error);
});
socket.on("close", (error) => {
console.log("Closed connection with ", socket.address());
});
}).listen({ port: 1754, host: "0.0.0.0" });
server.on("error", (error) => {
console.log("An error ocurred with the server", error);
});
server.on("close", () => {
console.log("Server closed connection");
});
};
mainFunction();
// Be sure to return the successful result type!
return BackgroundFetch.BackgroundFetchResult.NewData;
});
BTW It doesnt start if i dont add the mainFunction in useEffect
The code that i register my defined Task. (result returns undefined)
async function registerBackgroundFetchAsync() {
return BackgroundFetch.registerTaskAsync(BACKGROUND_CLIENT_TASK, {
minimumInterval: 5, // seconds
stopOnTerminate: false, // android only,
startOnBoot: true, // android only
});
}
const registerFunction = async () => {
const result = await registerBackgroundFetchAsync();
console.log(result);
console.log("resultup");
const status = await BackgroundFetch.getStatusAsync();
const isRegistered = await TaskManager.isTaskRegisteredAsync(
BACKGROUND_CLIENT_TASK
);
setStatus(status);
setIsRegistered(isRegistered);
};
registerFunction();

null is not an object (evaluating 'LoginManager.logInWithPermissions')

When I try to login to Facebook in expo android app, getting the following error
null is not an object (evaluating 'LoginManager.logInWithPermissions')
const SignInwithFB = async () => {
try {
await LoginManager.logInWithPermissions(["public_profile", "email"]);
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return;
}
const facebookCredential = FacebookAuthProvider.credential(data.accessToken);
const auth = getAuth(firebase);
const response = await signInwithCredential(auth, facebookCredential);
console.log(response);
} catch (e) {
console.log(e);
}
}
installed by following this instructions: https://www.npmjs.com/package/react-native-fbsdk-next
Check Expo installation section in npm install page, make sure you have implemented the instruction
const SignInwithFB = async () => {
try {
const loginManagerResult = await LoginManager.logInWithPermissions(["public_profile", "email"]);
if(loginManagerResult) {
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return;
}
const facebookCredential = FacebookAuthProvider.credential(data.accessToken);
const auth = getAuth(firebase);
const response = await signInwithCredential(auth, facebookCredential);
console.log(response);
}
} catch (e) {
console.log(e);
}
}

Error when use Audio.Sound.pauseAsync() in expo-av

This is my code
const [isPlaying, setIsPlaying] = useState(false);
const [playbackObject, setPlaybackObject] = useState(null as any);
const [playbackStatus, setPlaybackStatus] = useState(null as any);
const handleAudioPlayPause = async () => {
try {
if (playbackObject !== null && playbackStatus === null) {
const status = await playbackObject.loadAsync(
{ uri: audioUri },
{ shouldPlay: true }
);
setIsPlaying(true);
return setPlaybackStatus(status);
}
// // It will pause our audio
if (playbackStatus.isPlaying) {
const status = await playbackObject.pauseAsync();
setIsPlaying(false);
return setPlaybackStatus(status);
}
// It will resume our audio
if (!playbackStatus.isPlaying) {
const status = await playbackObject.playAsync();
setIsPlaying(true);
return setPlaybackStatus(status);
}
} catch (error) {
console.log('error in play/pause ', error);
}
};
the playAsync works fine, and playbackStatus.isPlaying change to true, but when pauseAsync() is executed it throws the following error:
[Error: Encountered an error while setting status!]
I was looking in the documentation and in different forums without a solution yet, I even used the same example and it gives me the same error

Create VIdeocall room with multiple users using WebRtc and firebase

i am trying to create a room video call something like Whatsapp with firebase as signalisation server for two users it works perfect as expected but when a third user join everything stop working
if the user A the first who join and the user B the second until the user C join everything work fine but when C join user A freeze and lost user B connection and B share screen with C but also sometimes freezing
here is my code
onst joinRoom = async () => {
const roomRef = await firestore().collection('meets').doc(params.callId);
roomRef
.collection('users')
.add({name, type: 'join'})
.then(() => {
roomRef
.collection('users')
.get()
.then(async querySnapshot => {
if (querySnapshot.empty) {
console.log('EMPTY');
} else {
querySnapshot.forEach(async snap => {
if (snap.data().name !== name && snap.data().type === 'join') {
// data.push(snap.data().name);
await creatOffer(snap.data().name);
}
// if (data.length > 0) {
// Promise.all(data).then(async user => {
// return await creatOffer(user);
// });
// }
});
}
});
});
// // listen on any new offers
roomRef.collection('offers').onSnapshot(data => {
data.docChanges().forEach(async change => {
if (change.type === 'added') {
// console.log('changes', change.doc.data());
if (change.doc.data().to === name) {
await createAnswer(change.doc.data().from, change.doc.data().offer);
}
}
});
});
//listen to answers
roomRef.collection('answers').onSnapshot(async snapshot => {
snapshot.docChanges().forEach(async change => {
if (change.type === 'added') {
const pc = pcPeers[change.doc.data().from];
if (change.doc.data().to === name) {
const rtcSessionDescription = new RTCSessionDescription(
change.doc.data().answer,
);
if (pc && rtcSessionDescription) {
await pc.setRemoteDescription(rtcSessionDescription);
}
}
}
});
});
//listen to candidate change
roomRef.collection('candidates').onSnapshot(async snapshot => {
snapshot.docChanges().forEach(async change => {
// console.log('answers', change.doc.data());
if (change.type === 'added') {
console.log('added', Platform.OS);
if (change.doc.data().to === name) {
const pc = pcPeers[change.doc.data().from];
// console.log(pc);
if (pc) {
await pc.addIceCandidate(
new RTCIceCandidate(change.doc.data().candidate),
);
}
}
}
});
});
};
and function to create offer
const creatOffer = async to => {
try {
const {roomRef, localPC} = await initializePeer(to);
const offer = await localPC.createOffer();
// console.log('offer', offer);
if (offer) {
await localPC.setLocalDescription(offer);
await roomRef.collection('offers').add({from: name, to, offer});
}
pcPeers = {...pcPeers, [to]: localPC};
} catch (e) {
console.log(e);
}
};
function to create answer
const createAnswer = async (from, offer) => {
try {
const {localPC, roomRef} = await initializePeer(from);
await localPC.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await localPC.createAnswer();
await localPC.setLocalDescription(answer);
// await checkIfAnswerAlreadyCreated(from, name);
await roomRef.collection('answers').add({from: name, to: from, answer});
pcPeers = {...pcPeers, [from]: localPC};
} catch (e) {
console.log(e);
}
};
and here is how i initialise a peer
setLocalStream(initialStream);
const roomRef = await firestore().collection('meets').doc(params.callId);
const collection = roomRef.collection('candidates');
localPC.onicecandidate = async e => {
if (!e.candidate) {
return;
}
// console.log('canditates', Platform.OS);
const state = localPC.iceGatheringState;
if (state !== 'complete') {
await collection.add({
from: name,
candidate: e.candidate.toJSON(),
to,
date: new Date(),
});
} else {
Alert.alert('tes');
}
// InCallManager.setForceSpeakerphoneOn(true);
// InCallManager.setSpeakerphoneOn(true);
};
localPC.onsignalingstatechange = async event => {
// when the signal state become stable record the data and stop ringback
if (event.target.signalingState === 'stable') {
if (Platform.OS === 'ios') {
localStream?.getVideoTracks().forEach(track => {
//For ios to trigger the camera on
track._switchCamera();
track._switchCamera();
});
}
}
};
localPC.onaddstream = e => {
if (e?.stream) {
// console.log(
// `RemotePC received the stream call ${Platform.OS}_${Platform.Version}`,
// e?.stream,
// );
console.log(Platform.OS, ' ', Platform.Version);
if (remoteStream === null) {
// Alert.alert('stream 1');
setRemoteStream(e?.stream);
} else {
// Alert.alert('stream 2');
setRemoteStream_(e?.stream);
}
}
};
return {localPC, roomRef};
};
can anyone help me with some hints where is tthe problem i’ve created for my self here and thank you

Getting pc.iceConnectionState Checking, failed in pc.oniceconnectionstatechange event in webRTC

I'm using webrtc for video calling in react native app.
If I call to someone else and receivers receives call then I get stream of receiver but there is a problem at receiver side.
Receiver gets remotestream but it shows blank view.
import AsyncStorage from '#react-native-async-storage/async-storage';
import {
RTCIceCandidate,
RTCPeerConnection,
RTCSessionDescription,
} from 'react-native-webrtc';
import io from '../scripts/socket.io';
const PC_CONFIG = {
iceServers: [
{ url: 'stun:motac85002'},
],
};
export const pc = new RTCPeerConnection(PC_CONFIG);
// Signaling methods
export const onData = data => {
handleSignalingData(data.data);
};
const ENDPOINT = 'http://52.52.75.250:3000/';
const socket = io(ENDPOINT);
// const PeerConnection = () => {
const sendData = async data => {
const roomId = await AsyncStorage.getItem('roomId');
const userId = parseInt(await AsyncStorage.getItem('user_id'));
socket.emit('data', roomId, userId, data);
};
export const createPeerConnection = async(stream, setUsers) => {
try {
pc.onicecandidate = onIceCandidate;
const userId = parseInt(await AsyncStorage.getItem('user_id'));
pc.onaddstream = e => {
setUsers(e.stream);
};
pc.addStream(stream)
pc.oniceconnectionstatechange = function () {
// console.log('ICE state: ', pc);
console.log('iceConnectionState', pc.iceConnectionState);
if (pc.iceConnectionState === "failed" ||
pc.iceConnectionState === "disconnected" ||
pc.iceConnectionState === "closed") {
console.log('iceConnectionState restart', userId);
// console.log('ICE state: ', pc);
// Handle the failure
pc.restartIce();
}
};
console.log('PeerConnection created', userId);
// sendOffer();
} catch (error) {
console.error('PeerConnection failed: ', error);
}
};
export const callSomeone = () => {
pc.createOffer({}).then(setAndSendLocalDescription, error => {
console.error('Send offer failed: ', error);
});
};
const setAndSendLocalDescription = sessionDescription => {
pc.setLocalDescription(sessionDescription);
sendData(sessionDescription);
};
const onIceCandidate = event => {
if (event.candidate) {
sendData({
type: 'candidate',
candidate: event.candidate,
});
}
};
export const disconnectPeer = () =>{
pc.close();
}
const sendAnswer = () => {
pc.createAnswer().then(setAndSendLocalDescription, error => {
console.error('Send answer failed: ', error);
});
};
export const handleSignalingData = data => {
switch (data.type) {
case 'offer':
pc.setRemoteDescription(new RTCSessionDescription(data));
sendAnswer();
break;
case 'answer':
pc.setRemoteDescription(new RTCSessionDescription(data));
break;
case 'candidate':
pc.addIceCandidate(new RTCIceCandidate(data.candidate));
break;
}
};
// }
// export default PeerConnection
Can anyone please tell me why at receiver side video stream is not displaying?
Also there is a remoteStream issue in motorola device. Why is this happening?
This statement:
const PC_CONFIG = {
iceServers: [
{ url: 'stun:motac85002'},
],
};
Has two potential issues:
First, the parameter for the iceServers object should be urls, not url. (Although it wouldn't surprise me if the browsers accepted either).
Second, as I mentioned in comments to your question, the STUN address itself looks to be a local address instead of an Internet address. That might explain why you aren't seeing any srflx or UDP candidates in the SDP. And as such, that might explain connectivity issues.
So instead of the above, could you try this:
const PC_CONFIG= {iceServers: [{urls: "stun:stun.stunprotocol.org"}]};