QR Code Scanner in Unity? - c#

I am trying to get QRCode reader in unity that works on ios and Android.
Unity Zxing QR code scanner integration
Using above answer I Have added Vuforia (Working perfectly alone). then i also have added Zxing.unity.dll in plugins folder, then added this script to ARCamera in a scene.
using UnityEngine;
using System;
using System.Collections;
using Vuforia;
using System.Threading;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
[AddComponentMenu("System/VuforiaScanner")]
public class VuforiaScanner : MonoBehaviour
{
private bool cameraInitialized;
private BarcodeReader barCodeReader;
void Start()
{
barCodeReader = new BarcodeReader();
StartCoroutine(InitializeCamera());
}
private IEnumerator InitializeCamera()
{
// Waiting a little seem to avoid the Vuforia's crashes.
yield return new WaitForSeconds(1.25f);
var isFrameFormatSet = CameraDevice.Instance.SetFrameFormat(Image.PIXEL_FORMAT.RGB888, true);
Debug.Log(String.Format("FormatSet : {0}", isFrameFormatSet));
// Force autofocus.
var isAutoFocus = CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
if (!isAutoFocus)
{
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
}
Debug.Log(String.Format("AutoFocus : {0}", isAutoFocus));
cameraInitialized = true;
}
private void Update()
{
if (cameraInitialized)
{
try
{
var cameraFeed = CameraDevice.Instance.GetCameraImage(Image.PIXEL_FORMAT.RGB888);
if (cameraFeed == null)
{
return;
}
var data = barCodeReader.Decode(cameraFeed.Pixels, cameraFeed.BufferWidth, cameraFeed.BufferHeight, RGBLuminanceSource.BitmapFormat.RGB24);
if (data != null)
{
// QRCode detected.
Debug.Log(data.Text);
}
else
{
Debug.Log("No QR code detected !");
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
}
}
But it is still not detecting any QRCode. Is there any other way to do QRcode reading and writing except Zxing? or any working sample project you have?

I also tried to implement a QRCode Reader with Vuforia and XZing using almost the same code you used. For me it worked, but it took very very long to detect the QRCode.
When I used a Color32 array instead of cameraFeed.pixels it was much quicker:
GUI.DrawTexture(screenRect, webCamTexture, ScaleMode.ScaleToFit);
try
{
IBarcodeReader barcodeReader = new BarcodeReader();
var result = barcodeReader.Decode(webCamTexture.GetPixels32(),
webCamTexture.width, webCamTexture.height);
if (result != null)
{
Debug.Log("DECODED TEXT FROM QR: " + result.Text);
loadNewPoi(Convert.ToInt32(result.Text));
PlayerPrefs.SetInt("camera_enabled", Convert.ToInt32(false));
webCamTexture.Stop();
}
}
But in this example I was using a WebCamTexture instead of Vuforia.
Unluckily it isn't possible to get a Color32 array with GetPixels32() from the Vuforia camera.
Another option is to use the QRCodes as Image-Targets, but I have a lot of wrong detections doing this.
For me there is no fitting solution for XZing together with Vuforia at the moment.

Related

Why doesn't Google Play Game authorization work in Unity?

I did everything right, I specified SHA1 in the Google API, Linked it all to Google Console, inserted resources and Web Client ID into Unity, but every time I try to log in, it writes "Canceled".
In LogCat I don't get errors, there are only:
*** [Play Games Plugin 0.11.01] 02.18.23 ERROR: Returning an error code
GooglePlayGames.OurUtils.PlayGamesHelperObject:Update()
Google Play services out of date for iae.perfectray.dogs. Reqires 21300000 but found 212621032
Here is the authorization code:
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Auth : MonoBehaviour
{
// Start is called before the first frame update
public Text text;
void Start()
{
PlayGamesPlatform.Activate();
PlayGamesPlatform.DebugLogEnabled = true;
}
public void Authh()
{
PlayGamesPlatform.Instance.Authenticate(ProccessAuth);
}
internal void ProccessAuth(SignInStatus status)
{
if(status == SignInStatus.Success)
{
text.text = "Status: Succesfull";
}
else
{
text.text = "Status: " + status;
}
}
I've already tried everything, nothing works(

Showing local pdf files from documents folder in xamarin ios webview [duplicate]

Im currently having an issue loading a local pdf into a webview. I have the code which works without any errors and when I run it on the iPad simulator, it works absolutely perfect. However, the issue comes when I try to run it on a physical iPad device. When I run it and it gets to the point where it needs to show the PDF, the webview loads but there is no PDF shown in the webview.
The PDF is actually generated by the app and I store it inside a directory inside the library folder.
Code to show the PDF in the WebView:
public void LoadPdfToWebView(string pdfPath)
{
//Console.WriteLine("Load request started");
WebView.LoadRequest(new NSUrlRequest(new NSUrl(pdfPath, false)));
View.AddSubview(WebView);
//Console.WriteLine("Load request Finished");
}
Not really sure why this would be the case and hopefully somebody can help.
I've just had to fix this for an app and thought I'd post the solution
This is for WKWebView which is a requirement from Apple as of Dec 2020 though the deadline has been temporarily extended
Xaml PdfWebView ContentPage
<controls:PdfWebView
Source="{Binding PDFSource}"
HeightRequest="1000"
WidthRequest="1000"/>
control
namespace XForms.Controls
{
public class PdfWebView : WebView { }
}
VM, only the relevant part
private string _pdfSource;
public string PDFSource
{
get => _pdfSource;
set
{
if (Device.RuntimePlatform == Device.Android && value.StartsWith("file:") == false)
{
value = $"file:///android_asset/pdfjs/web/viewer.html?file=file:///{WebUtility.UrlEncode(value)}";
}
SetProperty(ref _pdfSource, value);
}
}
iOS renderer for PdfWebView
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using XForms.Controls;
using WebKit;
using Foundation;
[assembly: ExportRenderer(typeof(PdfWebView), typeof(iOSUI.Renderers.PdfWebViewRenderer))]
namespace iOSUI.Renderers
{
public class PdfWebViewRenderer : ViewRenderer<WebView, WKWebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var wkWebViewConfiguration = new WKWebViewConfiguration();
var wkWebView = new WKWebView(Frame, wkWebViewConfiguration)
{
AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
};
SetNativeControl(wkWebView);
}
if (e.NewElement != null)
{
if (string.IsNullOrEmpty(((UrlWebViewSource)e.NewElement.Source)?.Url) == false)
{
var url = ((UrlWebViewSource)e.NewElement.Source).Url;
if(url.StartsWith("http"))
{
Control.LoadRequest(new NSUrlRequest(new NSUrl(url)));
}
else
{
Control.LoadFileUrl(new NSUrl($"file://{url}"), new NSUrl($"file://{url}"));
}
}
}
}
}
}
Android Renderer
using System.Net;
using Android.Content;
using Android.Views;
using Android.Webkit;
using XForms.Controls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(PdfWebView), typeof(AndroidUI.Renderers.PDFViewRenderer))]
namespace AndroidUI.Renderers
{
public class PDFViewRenderer : WebViewRenderer
{
public PDFViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.AllowFileAccess = true;
Control.Settings.AllowFileAccessFromFileURLs = true;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.SetWebChromeClient(new WebChromeClient());
}
}
// If you want to enable scrolling in WebView uncomment the following lines.
public override bool DispatchTouchEvent(MotionEvent e)
{
Parent.RequestDisallowInterceptTouchEvent(true);
return base.DispatchTouchEvent(e);
}
}
}
This solution uses pdfjs in Android and WKWebview in iOS to render the PDF
The PDFSource is the full path to the file, I use System.IO .net standard calls to handle this in a cross platform way
All the files are stored in (I have a method called GetFullPath to return the cross platform common path)
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Combined with a filename with Path.Combine
Path.Combine(GetFullPath(), fileName);
That is the PDFSource that gets set in the VM
The Pdfjs library files are just copied into Assets/pdfjs for Android
The magic for iOS is just calling LoadFileUrl instead of LoadRequest and prepending "file://"
I've slightly sanitised our namespaces so some of them wont resolve like XForms.Controls and so on that refer to our internal code
In Xamarin.IOS to show a document type other than HTML in a UIWebView:
Add the document (for example, a PDF) to your Xamarin.iOS project. Set the Build Action to BundleResource. You can set the build action for a file by right-clicking on that file and and choosing Build Action in the menu that opens.
Create a UIWebView and add it to a view:
webView = new UIWebView (View.Bounds);
View.AddSubview(webView);
Load the file using NSUrl and NSUrlRequest classes:
string fileName = "Loading a Web Page.pdf"; // remember case-sensitive
string localDocUrl = Path.Combine (NSBundle.MainBundle.BundlePath, fileName);
webView.LoadRequest(new NSUrlRequest(new NSUrl(localDocUrl, false)));
webView.ScalesPageToFit = true;
You can refer to this officical steps.If have problems or other needs, you can refer to this link
If you can't read the resources in the bundle, you can put the resource cache in the temp directory of the sandbox and try to read it using LoadRequest.

Problem / Error with converting M4A Audio File to MP3 using NAudio in C#

I'm in a process of creating a demo for an audio conversion software that I create as a hobby. I wanted converting an M4A (MPEG-4) audio file to an MP3 using a simple GUI for the user to interact. I also implemented a feature that allows the user to play the selected audio file (M4A) before conversion, which I have learned from watching NAudio video tutorials. However, I was stuck with a specific issue that stops me from progressing this demo project.
I have received an error right after the SaveFileDialogue selection to place the converted file (MP3) which prevents me from continuing the process. (I have put the error message in the comments for all of you to see in the method of btnConvertToMp3_Click()).
I have tried using MediaFoundationEncoder.EncodeToMp3() to solve this case. Unfortunately, I get an error, stating that there are "No available MP3 encoders" which I have researched that it is not fully supported enough to be used functionally for every audio format.
I have tried searching for more solutions, close to this problem but sadly could not find what I was hoping for, so I decided to ask if you have any input about this problem.
Here is my current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
using NAudio;
using NAudio.Lame;
using NAudio.Dmo;
using System.Windows.Forms;
namespace M4AtoMP3ConversionDEMO
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private NAudio.Wave.BlockAlignReductionStream stream = null;
private NAudio.Wave.DirectSoundOut output = null;
public void btnOpenM4AFile_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "M4A Audio File (*.m4a)|*.m4a;";
if (open.ShowDialog() != DialogResult.OK)
{
return;
}
MediaFoundationReader mfM4A = new MediaFoundationReader(open.FileName);
stream = new NAudio.Wave.BlockAlignReductionStream(mfM4A);
btnPlayPauseButton.Enabled = true;
btnConvertToMP3.Visible = true;
output = new NAudio.Wave.DirectSoundOut();
output.Init(mfM4A);
output.Play();
MessageBox.Show(".M4A Format has been accepted", ".M4A Audio Format", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnConvertToMP3_Click(object sender, EventArgs e)
{
DialogResult mb1 = MessageBox.Show("Are you sure you want to convert this M4A File?", "Converting to MP3", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
switch (mb1)
{
case DialogResult.Yes:
SaveFileDialog save = new SaveFileDialog();
save.Filter = "MP3 File (*.mp3)|*.mp3";
if (save.ShowDialog() != DialogResult.OK) return;
// Unable to cast COM object of type 'System.__ComObject' to interface type 'NAudio.MediaFoundation.IMFSourceReader'.
// This operation failed because the QueryInterface call on the COM component for the interface with IID '{70AE66F2-C809-4E4F-8915-BDCB406B7993}' failed due to the following error:
// No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))
using (var mp3FileReader = new LameMP3FileWriter(save.FileName, stream.WaveFormat, LAMEPreset.ABR_320))
{
stream.CopyTo(mp3FileReader);
}
break;
case DialogResult.No:
break;
}
}
private void btnPlayPauseButton_Click(object sender, EventArgs e)
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Pause();
Image playButton = new Bitmap(#"C:\Users\CeX\source\repos\AudioConverterUI-WorkInProgress\AudioConverterUI-WorkInProgress\Resources\play-button-size.png");
btnPlayPauseButton.Image = playButton;
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
{
output.Play();
Image pauseButton = new Bitmap(#"C:\Users\CeX\source\repos\AudioConverterUI-WorkInProgress\AudioConverterUI-WorkInProgress\Resources\pause-button-size.png");
btnPlayPauseButton.Image = pauseButton;
}
}
}
private void DisposeWave()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Stop();
output.Dispose();
output = null;
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
}
}
}
}
If there isn't a suitable solution to this error, is there a possible alternative or simple solution that would allow me to convert M4A to MP3 without using NAudio, even with GUI?
A simple approach without using NAudio (which relies on Windows codecs) is to use FFMPEG, and do a command line conversion.

Writing .txt file in android

I need help with a problem in our system. We are using unity and visual studio C# to create a mobile VR game using gaze controls only (no controller). We need to find a way to write debug logs into a text file and save to android internal storage. Thanks in advance for the help!!
That is our code below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine;
public class VRPlace : MonoBehaviour
{
...
void OnTriggerEnter(Collider other)
{
string path = "Assets/Resources/PlacesLog.txt";
StreamWriter testing = new StreamWriter(path, true);
if (other.gameObject.name == "Hospital")
{
GameObject otherObj = other.gameObject;
Debug.Log("Triggered to: " + otherObj);
}
testing.WriteLine(other.gameObject.name);
testing.Close();
}
}
here is a sample for saving a .txt file with StreamWriter.
class FileSaver
{
static void Main()
{
// Create a StreamWriter instance
StreamWriter writer = new
StreamWriter(Application.PersistentDataPath + "/droidlog.txt");
// This using statement will ensure the writer will be closed when no longer used
using(writer)
{
// Loop through the numbers from 1 to 20 and write them
for (int i = 1; i <= 20; i++)
{
writer.WriteLine(i);
}
}
}
}
this saves the numbers 1-20, you will want to fill in the blanks... good luck!

Reference to type 'ISerializable' claims it is defined in 'mscorelib'

I am using EmguCV in Unity 5.6.2f1 Personal to detect faces in a camera stream.
And it works just fine if I'm trying to run it in the built-in Editor/Game Output and there are no Errors in the Console.
However, when I'm trying to build it to Windows Store, specifically HoloLens, I'm getting 4 Errors in the Console:
Assets\OpenCVTest.cs(57,11): error CS7069: Reference to type 'ISerializable' claims it is defined in 'mscorlib', but it could not be found
Assets\OpenCVTest.cs(57,11): error CS7069: Reference to type 'ICloneable' claims it is defined in 'mscorlib', but it could not be found
Assets\OpenCVTest.cs(62,26): error CS7069: Reference to type 'ISerializable' claims it is defined in 'mscorlib', but it could not be found
Assets\OpenCVTest.cs(62,26): error CS7069: Reference to type 'ICloneable' claims it is defined in 'mscorlib', but it could not be found
It seems weird since it works just fine in the built-in preview, but not when I'm trying to export it.
the lines in question are
using (Image<Gray, byte> nextFrame = cap.QueryFrame ().ToImage<Gray, byte>()) {
Rectangle[] faces = cascade.DetectMultiScale(nextFrame, 1.4, 1);
and according to the line number it refers to Image in the one line and cascade (which is a CascadeClassifier) in the other.
A few google searches for different keywords, including the error-numbers didn't yield any helpful result. Similar questions on here weren't able to help me either, since the surroundings are completely different.
Here is my complete code, without all the unnecessary stuff:
using UnityEngine;
using System.Collections;
using Emgu.CV;
using Emgu.CV.Util;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.Util;
using System.Runtime.InteropServices;
using System;
using System.Drawing;
using System.Windows.Forms;
public class OpenCVTest : MonoBehaviour {
private VideoCapture cap;
private CascadeClassifier cascade;
private int counter;
private int intervall;
private GameObject border;
// Use this for initialization
void Start () {
counter = 0;
intervall = 6;
cap = new VideoCapture (0);
cascade = new CascadeClassifier ("haarcascade_frontalface_alt.xml");
border = Resources.Load ("Border") as GameObject;
}
// Update is called once per frame
void Update () {
counter++;
if (counter >= intervall) {
counter = 0;
using (Image<Gray, byte> nextFrame = cap.QueryFrame ().ToImage<Gray, byte>()) { //ERROR 1
if (nextFrame != null) {
Rectangle[] faces = cascade.DetectMultiScale(nextFrame, 1.4, 1); //ERROR 2
//remove preivious borders
var previous = GameObject.FindGameObjectsWithTag("Face");
foreach (var box in previous) {
Destroy (box.gameObject);
}
//instanciate new ones
foreach (var face in faces) {
GameObject newBorder = Instantiate (border);
newBorder.transform.position = new Vector3 (face.X / 100f, face.Y / -100f, 10);
}
}
}
}
}
}
all my EmguCV dll's are in Assets\Plugins.

Categories

Resources