I get this error:
Assets/initadmod.cs(25,2): error CS0118: Admob' is anamespace' but a type' was expected
Please copy this script to your MonoDevelop to see where is error.
using UnityEngine;
using System.Collections;
using Admob;
namespace Admob {
namespace GoogleMobileAds {
public class initadmod : MonoBehaviour {
public static initadmod instance;
// Use this for initialization
void Start () {
instance = this;
Debug.Log("start unity demo-------------");
initAdmob();
}
public string baner_Adr;
public string fullbaner_Adr;
public string baner_IOS ;
public string fullbaner_IOS ;
Admob ad;
//bool isAdmobInited = false;
void initAdmob()
{
string adUnitIdbaner ;
string adUnitIdfull ;
// isAdmobInited = true;
#if UNITY_EDITOR
adUnitIdbaner = "baner_Adr";
adUnitIdfull = "fullbaner_Adr";
#elif UNITY_ANDROID
adUnitIdbaner = baner_Adr;
adUnitIdfull = fullbaner_Adr;
#elif UNITY_5 || UNITY_IOS || UNITY_IPHONE
adUnitIdbaner = baner_IOS;
adUnitIdfull = fullbaner_IOS;
#else
adUnitIdbaner = baner_Adr;
adUnitIdfull = fullbaner_Adr;
#endif
ad = Admob.Instance();
ad.bannerEventHandler += onBannerEvent;
ad.interstitialEventHandler += onInterstitialEvent;
ad.rewardedVideoEventHandler += onRewardedVideoEvent;
ad.nativeBannerEventHandler += onNativeBannerEvent;
ad.initAdmob(adUnitIdbaner, adUnitIdfull);
// ad.setTesting(true);
Debug.Log("admob inited -------------");
}
public bool ShowBanerOnPlay;
public bool _ShowFullOnBackToMainMenu;
public bool _ShowFullNowOnOpenGame;
public int ShowFullOndie;
/// <summary>
/// hiện baner nhỏ góc trên màn hình lúc chạy
/// </summary>
public void ShowBanerOnPlayGame()
{
if (ShowBanerOnPlay)
{
ShowBaner();
}
}
/// <summary>
/// hiện baner lúc chết
/// sau Showfullondie số lần chết mới cho hiện
/// </summary>
public void ShowFullOnDie()
{
if (UImanager.uimanager.showbane >= ShowFullOndie-1)
{
showInterstitial();
UImanager.uimanager.showbane = 0;
}
}
/// <summary>
/// hiện qc khi đến menu chính
/// </summary>
public void ShowFullOnBackToMainMenu()
{
if (_ShowFullOnBackToMainMenu)
{
showInterstitial();
}
}
/// <summary>
/// hiện quảng cáo khi mới mở game ra khi hết mục dowload
/// </summary>
public void ShowFullNowOnOpenGame()
{
if (_ShowFullNowOnOpenGame)
{
showInterstitial();
}
}
void showInterstitial()
{
if (ad.isInterstitialReady())
{
ad.showInterstitial();
}
else
{
ad.loadInterstitial();
}
}
void ShowBaner()
{
Admob.Instance().showBannerRelative(AdSize.SmartBanner, AdPosition.TOP_CENTER, 0);
}
public void HideBaner()
{
Admob.Instance().removeBanner();
}
void onInterstitialEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobEvent---" + eventName + " " + msg);
if (eventName == AdmobEvent.onAdLoaded)
{
Admob.Instance().showInterstitial();
}
}
void onBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobBannerEvent---" + eventName + " " + msg);
}
void onRewardedVideoEvent(string eventName, string msg)
{
Debug.Log("handler onRewardedVideoEvent---" + eventName + " " + msg);
}
void onNativeBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobNativeBannerEvent---" + eventName + " " + msg);
}
}
}
}
On line 25 you are declaring
Admob ad;
but Admob is a namespace, not a class, so you need to add the class to your declaration, maybe something like (this is just an example)
Admob.GoogleMobileAds.initadmod ad;
private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();
private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();
private static final long DELAY = 1000;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private long startTime = 0L;
int num = 1;
List<VideoModel> videoList;
private Handler customHandler = new Handler();
private static final String TAG = "RecordVideoActivity";
private String videoName;
static {
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
static {
INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
}
private AutoFitTextureView mTextureView;
private ImageButton mRecordButton;
private ImageView mDots;
private ImageButton mCheckPoint;
private CameraDevice mCameraDevice;
private CameraCaptureSession mPreviewSession;
private TextureView.SurfaceTextureListener mSurfaceTextureListener
= new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
int width, int height) {
openCamera(width, height);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
int width, int height) {
configureTransform(width, height);
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
private Size mPreviewSize;
private Size mVideoSize;
private MediaRecorder mMediaRecorder;
private boolean mIsRecordingVideo;
private HandlerThread mBackgroundThread;
private Handler mBackgroundHandler;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice cameraDevice) {
mCameraDevice = cameraDevice;
startPreview();
mCameraOpenCloseLock.release();
if (null != mTextureView) {
configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
}
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
finish();
}
};
private Integer mSensorOrientation;
private String mNextVideoAbsolutePath;
private CaptureRequest.Builder mPreviewBuilder;
private CameraManager manager;
private String cameraId;
private boolean isFlashSupported;
private ImageButton flashButton;
private ImageButton switchCamera;
private ImageButton revertVideo;
public static final String CAMERA_BACK = "0";
private TextView mChronometer;
private String flashOpt;
private long lastSavedTime;
private String prepend;
private static Size chooseVideoSize(Size[] choices) {
for (Size size : choices) {
if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 1080) {
return size;
}
}
Log.e(TAG, "Couldn't find any suitable video size");
return choices[choices.length - 1];
}
private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
// Collect the supported resolutions that are at least as big as the preview Surface
List<Size> bigEnough = new ArrayList<>();
int w = aspectRatio.getWidth();
int h = aspectRatio.getHeight();
for (Size option : choices) {
if (option.getHeight() == option.getWidth() * h / w &&
option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else {
Log.e(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera2_video_image);
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (dir.isDirectory()) {
deleteDirectory(dir);
}
videoList = new ArrayList<>();
mTextureView = findViewById(R.id.textureView);
mRecordButton = findViewById(R.id.videoOnlineImageButton);
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint = findViewById(R.id.checkPoint);
mCheckPoint.setVisibility(View.GONE);
mDots = findViewById(R.id.dot);
mRecordButton.setOnClickListener(this);
flashButton = findViewById(R.id.flashVideo);
switchCamera = findViewById(R.id.switchVideo);
revertVideo = findViewById(R.id.revertVideo);
revertVideo.setVisibility(View.GONE);
mChronometer = findViewById(R.id.chronometer);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
flashOpt = prefs.getString(getString(R.string.flash_option), getString(R.string.auto));
if (flashOpt.equals(getString(R.string.flash_off)))
flashButton.setImageResource(R.drawable.flash_auto);
else if (flashOpt.equals(getString(R.string.flash_on)))
flashButton.setImageResource(R.drawable.flash_on);
else
flashButton.setImageResource(R.drawable.flash_off);
findViewById(R.id.checkPoint).setOnClickListener(this);
findViewById(R.id.flashVideo).setOnClickListener(this);
findViewById(R.id.switchVideo).setOnClickListener(this);
findViewById(R.id.revertVideo).setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
startBackgroundThread();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
if(mIsRecordingVideo)
mRecordButton.setImageResource(R.drawable.ic_video_stop);
else
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint.setEnabled(true);
startTime=SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
#Override
public void onPause() {
closeCamera();
mCheckPoint.setEnabled(false);
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
stopBackgroundThread();
super.onPause();
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int hour = mins / 60;
mChronometer.setText("" + hour + ":"
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.videoOnlineImageButton: {
if (mIsRecordingVideo) {
mDots.setVisibility(View.GONE);
mChronometer.setVisibility(View.GONE);
switchCamera.setVisibility(View.VISIBLE);
mCheckPoint.setVisibility(View.GONE);
stopRecordingVideo();
Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mNextVideoAbsolutePath)));
sendBroadcast(mediaStoreUpdateIntent);
} else {
mCheckPoint.setVisibility(View.VISIBLE);
switchCamera.setVisibility(View.GONE);
mChronometer.setVisibility(View.VISIBLE);
mDots.setVisibility(View.VISIBLE);
startRecordingVideo();
}
break;
}
case R.id.switchVideo: {
facingCamera = !facingCamera;
closeCamera();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
break;
}
case R.id.flashVideo: {
if (onFlashCheck()) {
CameraCharacteristics cameraCharacteristics = null;
try {
cameraCharacteristics = manager.getCameraCharacteristics(cameraId);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Boolean available = cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
isFlashSupported = available == null ? false : available;
switchFlash();
}
break;
}
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#SuppressLint("MissingPermission")
private void openCamera(int width, int height) {
final Activity activity = this;
if (null == activity || activity.isFinishing()) {
return;
}
manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
Log.d(TAG, "tryAcquire");
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
cameraId = manager.getCameraIdList()[1];
if (facingCamera) {
cameraId = manager.getCameraIdList()[1];
flashButton.setVisibility(View.GONE);
} else {
cameraId = manager.getCameraIdList()[0];
flashButton.setVisibility(View.VISIBLE);
}
// Choose the sizes for camera preview and video recording
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics
.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
if (map == null) {
throw new RuntimeException("Cannot get available preview/video sizes");
}
mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
width, height, mVideoSize);
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
} else {
mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
}
configureTransform(width, height);
mMediaRecorder = new MediaRecorder();
manager.openCamera(cameraId, mStateCallback, null);
} catch (CameraAccessException e) {
Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
activity.finish();
} catch (NullPointerException e) {
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.");
}
}
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
closePreviewSession();
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mMediaRecorder) {
mMediaRecorder.release();
mMediaRecorder = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.");
} finally {
mCameraOpenCloseLock.release();
}
}
private void startPreview() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
Surface previewSurface = new Surface(texture);
mPreviewBuilder.addTarget(previewSurface);
mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
mPreviewSession = session;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession session) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if (null == mCameraDevice) {
return;
}
try {
setUpCaptureRequestBuilder(mPreviewBuilder);
HandlerThread thread = new HandlerThread("CameraPreview");
thread.start();
mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
if (onFlashCheck()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.VISIBLE);
}
});
if (flashOpt.equals(getString(R.string.auto)))
builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
else if (flashOpt.equals(getString(R.string.flash_off)))
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
else
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
} else
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.GONE);
}
});
}
private void configureTransform(int viewWidth, int viewHeight) {
if (null == mTextureView || null == mPreviewSize) {
return;
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / mPreviewSize.getHeight(),
(float) viewWidth / mPreviewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
}
mTextureView.setTransform(matrix);
}
private void setUpMediaRecorder() throws IOException {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
File file = getVideoFilePath(this);
mNextVideoAbsolutePath = file.getAbsolutePath();
videoName = file.getName();
mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);
mMediaRecorder.setVideoEncodingBitRate(10000000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
switch (mSensorOrientation) {
case SENSOR_ORIENTATION_DEFAULT_DEGREES:
mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
break;
case SENSOR_ORIENTATION_INVERSE_DEGREES:
mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
break;
}
mMediaRecorder.prepare();
}
private File getVideoFilePath(Context context) {
File appDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (!appDir.isDirectory()) {
appDir.mkdirs();
}
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "VIDEO_" + timestamp + ".mp4";
File videoFile = null;
try {
videoFile = File.createTempFile(prepend, ".mp4", appDir);
} catch (IOException e) {
e.printStackTrace();
}
return videoFile;
}
private void startRecordingVideo() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
setUpMediaRecorder();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
List<Surface> surfaces = new ArrayList<>();
// Set up Surface for the camera preview
Surface previewSurface = new Surface(texture);
surfaces.add(previewSurface);
mPreviewBuilder.addTarget(previewSurface);
// Set up Surface for the MediaRecorder
Surface recorderSurface = mMediaRecorder.getSurface();
surfaces.add(recorderSurface);
mPreviewBuilder.addTarget(recorderSurface);
mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull final CameraCaptureSession cameraCaptureSession) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPreviewSession = cameraCaptureSession;
updatePreview();
mIsRecordingVideo = true;
startTime = SystemClock.uptimeMillis();
mChronometer.setVisibility(View.VISIBLE);
customHandler.postDelayed(updateTimerThread, 0);
mRecordButton.setImageResource(R.drawable.ic_video_stop);
mMediaRecorder.start();
mCheckPoint.setEnabled(true);
}
});
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException | IOException e) {
e.printStackTrace();
}
}
private void closePreviewSession() {
if (mPreviewSession != null) {
mPreviewSession.close();
mPreviewSession = null;
}
}
#SuppressLint("ResourceType")
private void stopRecordingVideo() {
mIsRecordingVideo = false;
customHandler.removeCallbacks(updateTimerThread);
mRecordButton.setImageResource(R.drawable.ic_video);
if(mMediaRecorder!=null) {
try {
mMediaRecorder.stop();
} catch (RuntimeException e) {
e.printStackTrace();
}
mMediaRecorder.reset();
}
}
static class CompareSizesByArea implements Comparator<Size> {
#Override
public int compare(Size lhs, Size rhs) {
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
}
#Override
protected void onDestroy() {
customHandler.removeCallbacks(updateTimerThread);
}
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
Change aspect ratio values in AutoFitTextureView class or use Textureview instead of AutoFitTextureview.
I want to drag and drop a custom QGraphicsRectItem from one Graphicsview into another. I tried it with the QGraphicsSceneDragDropEvents and the QDragEnterEvent,QDropEvent, etc.
(I know I don´t need all of these includes).
Layout.h
#ifndef LAYOUT_H
#define LAYOUT_H
#include <QtWidgets/QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QtWidgets>
#include <QObject>
#include <QCursor>
#include <QDrag>
#include "ui_layout.h"
#include "GrRectItm_WorkRect.h"
#include <QGraphicsSceneDragDropEvent>
#include <QBrush>
#include <QGraphicsSceneDragDropEvent>
class Layout : public QObject, public QMainWindow
{
Q_OBJECT
public:
Layout(QWidget *parent = 0);
~Layout();
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);
/*void dragEnterEvent(QGraphicsSceneDragDropEvent *event) ;
void dragMoveEvent(QGraphicsSceneDragDropEvent *event) ;
void dragLeaveEvent(QGraphicsSceneDragDropEvent *event) ;
void dropEvent(QGraphicsSceneDragDropEvent *event) ;*/
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
//void mousePressEvent(QMouseEvent *event);
private:
Ui::LayoutClass ui;
QGraphicsScene *tb;
QGraphicsScene *wa;
int mX;
int mY;
QPoint mousePosition;
QGraphicsRectItem *rect;
QBrush blueBrush = (Qt::blue);
QBrush redBrush = (Qt::red);
QBrush greenBrush = (Qt::green);
QPen blackPen = (Qt::black);
QBrush rectColor ;
QString str_text;
bool selected;
void newRect();
signals:
public slots:
void changeColor();
void changeText();
void deleteRect();
};
#endif // LAYOUT_H
Layout.cpp
#include "layout.h"
#include <QtWidgets>
#include <QGraphicsItem>
#include"GrRectItm_WorkRect.h"
#include <QGraphicsView>
GrRectItm_WorkRect *rectItem;
GrRectItm_WorkRect *location;
QList < GrRectItm_WorkRect *> items;
Layout::Layout(QWidget *parent)
: QMainWindow(parent)
{
qDebug() << "Programm startet";
ui.setupUi(this);
tb = new QGraphicsScene(this);
wa = new QGraphicsScene(this);
ui.gv_ToolBar->setScene(tb);
ui.gv_WorkArea->setScene(wa);
ui.gv_ToolBar->setAcceptDrops(true);
ui.gv_WorkArea->setAcceptDrops(true);
ui.gv_WorkArea->setDragMode(QGraphicsView::ScrollHandDrag);
blackPen.setWidth(1);
rect = tb->addRect(10, 0, 90, 50, blackPen, blueBrush);
//rect->setFlag(QGraphicsItem::ItemIsSelectable);
QObject::connect(ui.btn_Change, SIGNAL(clicked()), this,
SLOT(changeColor()));
QObject::connect(ui.btn_Delete, SIGNAL(clicked()), this, SLOT(deleteRect()));
}
//void Layout::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
void Layout::dragEnterEvent(QDragEnterEvent *event) {
qDebug() << "dragEnterEvent startet";
event->acceptProposedAction();
}
//void Layout::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
void Layout::dragMoveEvent(QDragMoveEvent *event) {
qDebug() << "dragMoveEvent startet";
event->acceptProposedAction();
}
void Layout::dropEvent(QDropEvent *event) {
//void Layout::dropEvent(QGraphicsSceneDragDropEvent *event) {
qDebug() << "dropEvent startet";
QRectF rect123(0, 0, 70, 40);
mX = mousePosition.x();
mY = mousePosition.y();
str_text = ui.le_Name->text();
rectItem = new GrRectItm_WorkRect(str_text);
//newRect();
wa->addItem(rectItem);
rectItem->setRect(rect123);
rectItem->setPos(mX, mY);
rectItem->setBrush(greenBrush);
items.append(rectItem);
}
//void Layout::mousePressEvent(QGraphicsSceneMouseEvent *event) {
void Layout::mousePressEvent(QMouseEvent *event) {
qDebug() << "MousePressEvent startet";
mousePosition = event->pos();
mousePosition = mapToParent(event->pos() - mousePosition);
//if (rect->contains(mousePosition)) {
QPixmap *pix = new QPixmap(100, 50);
pix->fill(Qt::red);
QDrag *drag = new QDrag(this);
QMimeData *mime = new QMimeData;
drag->setMimeData(mime);
drag->setPixmap(*pix);
Qt::DropAction dropAction = drag->exec();
//}
}
void Layout::newRect() {
QString color = ui.cb_color->currentText();
QString text = ui.le_Name->text();
if (color == "Rot") {
rectItem->setBrush(redBrush);
rectItem->GrRectItm_WorkRect::setRectText(text);
}
else if (color == "Gruen") {
rectItem->setBrush(greenBrush);
rectItem->GrRectItm_WorkRect::setRectText(text);
}
else if (color == "Blau") {
rectItem->setBrush(blueBrush);
rectItem->GrRectItm_WorkRect::setRectText(text);
}
}
void Layout::changeColor() {
QString color = ui.cb_color->currentText();
QString text = ui.le_Name->text();
for (int i = 0; i < items.length(); i++) {
location = items.at(i);
selected = location->isSelected();
if (selected) {
rectItem = items.at(i);
try
{
newRect();
}
catch (const std::exception&)
{
continue;
}
}
}
}
void Layout::deleteRect() {
for (int i = 0; i < items.length(); i++) {
rectItem = items.at(i);
selected = rectItem->isSelected();
if (selected) {
try
{
rectItem->~GrRectItm_WorkRect();
items.removeAt(i);
i--;
}
catch (const std::exception&)
{
continue;
}
}
}
}
void Layout::changeText() {
QString text = ui.le_Name->text();
rectItem->GrRectItm_WorkRect::setRectText(text);
}
void Layout::mouseReleaseEvent(QMouseEvent *event) {
mousePosition = event->pos() - mousePosition;
}
Layout::~Layout()
{
}
I have my game with facebook invite integrated using unity3d. When switched to Android, everything works fine but when I switch to WebGL, I get the following error:
error CS0103: The name `LoggedSuccefull' does not exist in the current context
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.SceneManagement;
#if FACEBOOK
using Facebook.Unity;
#endif
public class FacebookManager : MonoBehaviour {
private bool LoginEnable;
public GameObject facebookButton;
//1.3.3
private string lastResponse = string.Empty;
public static string userID;
public static List<FriendData> Friends = new List<FriendData> ();
public bool logged;
protected string LastResponse {
get {
return this.lastResponse;
}
set {
this.lastResponse = value;
}
}
private string status = "Ready";
protected string Status {
get {
return this.status;
}
set {
this.status = value;
}
}
bool loginForSharing;
public static FacebookManager THIS;
void Awake () {
if (THIS == null)
THIS = this;
else if (THIS != this)
Destroy (gameObject);
DontDestroyOnLoad (this);
}
void OnEnable () {
#if PLAYG
NetworkManager.OnLoginEvent += GetUserName;
#endif
}
void OnLevelWasLoaded () {
if (logged && SceneManager.GetActiveScene ().name == "game")
LoggedSuccefull ();
}
void OnDisable () {
#if PLAYG
NetworkManager.OnLoginEvent -= GetUserName;
#endif
}
#if PLAYG || GAMESPARKS
public FriendData GetCurrentUserAsFriend () {
//code
}
#endif
#region FaceBook_stuff
#if FACEBOOK
public void CallFBInit () {
Debug.Log ("init facebook");
FB.Init (OnInitComplete, OnHideUnity);
}
private void OnInitComplete () {
Debug.Log ("FB.Init completed: Is user logged in? " + FB.IsLoggedIn);
if (FB.IsLoggedIn) {//1.3
CallFBLogin ();
}
}
private void OnHideUnity (bool isGameShown) {
Debug.Log ("Is game showing? " + isGameShown);
}
void OnGUI () {
if (LoginEnable) {
CallFBLogin ();
LoginEnable = false;
}
}
public void CallFBLogin () {
Debug.Log ("login");
FB.LogInWithReadPermissions (new List<string> () { "public_profile", "email", "user_friends" }, this.HandleResult);
}
public void CallFBLoginForPublish () {
FB.LogInWithPublishPermissions (new List<string> () { "publish_actions" }, this.HandleResult);
}
public void CallInvite () {
this.Status = "Logged FB.AppEvent";
FB.Mobile.AppInvite (new Uri ("//URI Here"), callback: this.HandleResultInvite);
// NOTE !! create your app link here https://developers.facebook.com/quickstarts/?platform=app-links-host
}
protected void HandleResultInvite (IResult result) {
if (result == null) {
this.LastResponse = "Null Response\n";
Debug.Log (this.LastResponse);
return;
}
// Some platforms return the empty string instead of null.
if (!string.IsNullOrEmpty (result.Error)) {
this.Status = "Error - Check log for details";
this.LastResponse = "Error Response:\n" + result.Error;
Debug.Log (result.Error);
} else if (result.Cancelled) {
this.Status = "Cancelled - Check log for details";
this.LastResponse = "Cancelled Response:\n" + result.RawResult;
Debug.Log (result.RawResult);
} else if (!string.IsNullOrEmpty (result.RawResult)) {
this.Status = "Success - Check log for details";
this.LastResponse = "Success Response:\n" + result.RawResult;
} else {
this.LastResponse = "Empty Response\n";
Debug.Log (this.LastResponse);
}
}
public void CallFBLogout () {
FB.LogOut ();
//code
}
public void Share () {
if (!FB.IsLoggedIn) {
//code
}
protected void HandleResult (IResult result) {
if (result == null) {
this.LastResponse = "Null Response\n";
Debug.Log (this.LastResponse);
return;
}
// this.LastResponseTexture = null;
// Some platforms return the empty string instead of null.
if (!string.IsNullOrEmpty (result.Error)) {
this.Status = "Error - Check log for details";
this.LastResponse = "Error Response:\n" + result.Error;
Debug.Log (result.Error);
} else if (result.Cancelled) {
this.Status = "Cancelled - Check log for details";
this.LastResponse = "Cancelled Response:\n" + result.RawResult;
Debug.Log (result.RawResult);
} else if (!string.IsNullOrEmpty (result.RawResult)) {
this.Status = "Success - Check log for details";
this.LastResponse = "Success Response:\n" + result.RawResult;
LoggedSuccefull ();//1.3
} else {
this.LastResponse = "Empty Response\n";
Debug.Log (this.LastResponse);
}
}
void LoggedSuccefull () {//1.3
logged = true;
facebookButton.SetActive (false);//1.3.3
if (PlayerPrefs.GetInt ("Facebook_Logged") == 0) {
GameObject rewardPopup = Instantiate (Resources.Load ("Reward")) as GameObject;
rewardPopup.transform.GetChild (0).GetComponent<RewardIcon> ().SetIconSprite (0);
InitScript.Instance.AddGems (10);
}
PlayerPrefs.SetInt ("Facebook_Logged", 1);
PlayerPrefs.Save ();
if (SceneManager.GetActiveScene ().name != "game")
return;
//Debug.Log(result.RawResult);
userID = AccessToken.CurrentAccessToken.UserId;
GetPicture (AccessToken.CurrentAccessToken.UserId);
}
void GetUserName () {
FB.API ("/me?fields=first_name", HttpMethod.GET, GettingNameCallback);
}
private void GettingNameCallback (IGraphResult result) {
if (string.IsNullOrEmpty (result.Error)) {
IDictionary dict = result.ResultDictionary as IDictionary;
string fbname = dict ["first_name"].ToString ();
#endif
}
}
void GetPicture (string id) {
FB.API ("/" + id + "/picture", HttpMethod.GET, this.ProfilePhotoCallback);
}
private void ProfilePhotoCallback (IGraphResult result) {
if (string.IsNullOrEmpty (result.Error) && result.Texture != null) {
Sprite sprite = new Sprite ();
sprite = Sprite.Create (result.Texture, new Rect (0, 0, 50, 50), new Vector2 (0, 0), 1f);
InitScript.profilePic = sprite;
#endif
}
}
public void SaveScores () {
//code
}
public void ReadScores () {
FB.API ("/me/objects/object", HttpMethod.GET, APICallBack);
}
public void GetFriendsPicture () {
FB.API ("me/friends?fields=picture", HttpMethod.GET, RequestFriendsCallback);
}
private void RequestFriendsCallback (IGraphResult result) {
if (!string.IsNullOrEmpty (result.RawResult)) {
// Debug.Log (result.RawResult);
//code
}
//}
}
//print(firstGroup["id"] + " " + firstGroup["title"]);
}
//this.gamerGroupCurrentGroup = (string)firstGroup["id"];
}
}
if (!string.IsNullOrEmpty (result.Error)) {
Debug.Log (result.Error);
}
}
}
public void GetPictureByURL (string url, FriendData friend) {
StartCoroutine (GetPictureCor (url, friend));
}
IEnumerator GetPictureCor (string url, FriendData friend) {
Sprite sprite = new Sprite ();
WWW www = new WWW (url);
yield return www;
sprite = Sprite.Create (www.texture, new Rect (0, 0, 50, 50), new Vector2 (0, 0), 1f);
friend.picture = sprite;
// print ("get picture for " + url);
}
public void APICallBack (IGraphResult result) {
Debug.Log (result);
}
#endif
#endregion
}
public class FriendData {
public string userID;
public string FacebookID;
public Sprite picture;
public int level;
public GameObject avatar;
}
Any help would be highly appreciated
I need to do this for one of my subject to get passed.This is the code and my problem is at PDA::class pda_ipari : public pda_basic where i need to create a namespace which has a derived class from an other namespace. Could you help me ?
#include <iostream>
using namespace std;
namespace PDA{
class pda_basic{
private :
float cpu_ghz;
int cpu_core;
int memory;
int storage;
public :
float getGhz()
{
return cpu_ghz;
}
void setGhz(float m)
{
cpu_ghz=m;
}
int getCore()
{
return cpu_core;
}
void setCore(int m)
{
cpu_core=m;
}
int getMemory()
{
return memory;
}
void setMemory(int m)
{
memory=m;
}
int getStorage()
{
return storage;
}
void setStorage(int m)
{
storage=m;
}
};
}
namespace abtu9p_pda{
PDA::class pda_ipari : public pda_basic {
private:
float display;
string vonalkodTipus;
int ip_vedelem;
public:
float getDisplay()
{
return display;
}
void setDisplay(float m)
{
display=m;
}
string getVonalkod()
{
return vonalkodTipus;
}
void setVonalkod(string m)
{
vonalkodTipus=m;
}
int getIP()
{
return ip_vedelem;
}
void setIP(int m)
{
ip_vedelem=m;
}
};
}
int main()
{
PDA::pda_basic tablet;
tablet.setGhz(2.7);
cout <<tablet.getGhz()<<endl;
return 0;
}