Skip to content

Instantly share code, notes, and snippets.

@anhtuank7c
Created January 31, 2017 05:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anhtuank7c/dff446b5168321e4b96f602ef9d818fe to your computer and use it in GitHub Desktop.
Save anhtuank7c/dff446b5168321e4b96f602ef9d818fe to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { View, Platform } from 'react-native';
import {
RTCPeerConnection,
RTCMediaStream,
RTCIceCandidate,
RTCSessionDescription,
RTCView,
MediaStreamTrack,
getUserMedia,
} from 'react-native-webrtc';
const configuration = { "iceServers": [{ "url": "stun:stun.l.google.com:19302" }] };
const pc = new RTCPeerConnection(configuration);
pc.createOffer(function (desc) {
pc.setLocalDescription(desc, function () {
// Send pc.localDescription to peer
}, function (e) { });
}, function (e) { });
pc.onicecandidate = (event) => {
// send event.candidate to peer
};
pc.onaddstream = (event) => {
console.log('onaddstream', event);
}
logError = (error) => {
throw error;
}
class Main extends Component {
state = {
videoURL: null
}
getLocalStream(isFront, callback) {
MediaStreamTrack.getSources(sourceInfos => {
console.log('sourceInfos', sourceInfos);
let videoSourceId;
for (const i = 0; i < sourceInfos.length; i++) {
const sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'video' && sourceInfo.facing === (isFront ? 'front' : 'back')) {
videoSourceId = sourceInfo.id;
}
}
getUserMedia({
audio: true,
video: Platform.OS === 'ios' ? false :
{
mandatory: {
minWidth: 300, // Provide your own width, height and frame rate here
minHeight: 300,
minFrameRate: 30
},
facingMode: (isFront ? 'user' : 'environment'),
optional: (videoSourceId ? [{ sourceId: videoSourceId }] : [])
}
}, function (stream) {
callback(stream);
}, logError);
});
}
componentDidMount() {
this.getLocalStream(true, (stream) => {
this.setState({
videoURL: stream.toURL()
});
console.log('getLocalStream OK', stream);
pc.addStream(stream);
});
}
render() {
return (
<View style={{ flex: 1, backgroundColor: '#ccc' }}>
<RTCView streamURL={this.state.videoURL} style={{ width: 300, height: 300, borderWidth: 1 }} />
</View>
);
}
}
export default Main;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment