Exemplo n.º 1
0
        public void OpenFile(string path, string fileName)
        {

        try
        {

            var documentsPath = path;
            var filePath = Path.Combine(documentsPath, fileName);

            //Device.OpenUri(new Uri(filePath));
            var PreviewController = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filePath));
            PreviewController.Delegate = new UIDocumentInteractionControllerDelegateClass(UIApplication.SharedApplication.KeyWindow.RootViewController);
            Device.BeginInvokeOnMainThread(() =>
            {
                PreviewController.PresentPreview(true);
            });

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        }
Exemplo n.º 2
0
        // MUST BE CALLED FROM THE UI THREAD
        public async Task Show(string title, string message, string filePath)
        {
            // need custmize for share app
            var items = new NSObject[] { NSObject.FromObject(title), NSUrl.FromFilename(filePath) };

            var activityController = new UIActivityViewController(items, null);
            var vc = GetVisibleViewController();

            NSString[] excludedActivityTypes = null;

            if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
            {
                activityController.ExcludedActivityTypes = excludedActivityTypes;
            }

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                if (activityController.PopoverPresentationController != null)
                {
                    activityController.PopoverPresentationController.SourceView = vc.View;
                }
            }
            await vc.PresentViewControllerAsync(activityController, true);
        }
        public void LoadHtmlAsync_NSUrl()
        {
            var    completed = false;
            string d         = Path.Combine(NSBundle.MainBundle.ResourcePath, "access-denied.html");
            string g         = Path.Combine(NSBundle.MainBundle.ResourcePath, "access-granted.html");

            TestRuntime.RunAsync(DateTime.Now.AddSeconds(3000), async() => {
                using (var denied = NSUrl.FromFilename(d))
                    using (var granted = NSUrl.FromFilename(g)) {
                        var options = new NSAttributedStringDocumentAttributes {
                            ReadAccessUrl = granted
                        };
                        var r1 = await NSAttributedString.LoadFromHtmlAsync(granted, options);
                        Assert.That(r1.AttributedString.Value, Is.EqualTo("Granted"), "granted by options");
#if false
                        // this does not match my interpretation of the (headers) docs
                        var r2 = await NSAttributedString.LoadFromHtmlAsync(denied, options);
                        Assert.That(r2.AttributedString.Value, Is.Not.EqualTo("Denied"), "denied by options");
#endif
                        completed = true;
                    }
            }, () => completed);
            Assert.True(completed, "completed");
        }
Exemplo n.º 4
0
        public Task <bool> Move(string fromPath, string toPath)
        {
            var tcs = new TaskCompletionSource <bool> ();

            var fromLocalPath = GetLocalPath(fromPath);
            var toLocalPath   = GetLocalPath(toPath);

            var fromUrl = NSUrl.FromFilename(fromLocalPath);
            var toUrl   = NSUrl.FromFilename(toLocalPath);

            var     c = new NSFileCoordinator(filePresenterOrNil: (INSFilePresenter)null);
            NSError coordErr;

            c.CoordinateReadWrite(fromUrl, NSFileCoordinatorReadingOptions.WithoutChanges, toUrl, NSFileCoordinatorWritingOptions.ForReplacing, out coordErr, (newFromUrl, newToUrl) => {
                try {
                    var man = new NSFileManager();
                    NSError moveErr;

                    var r = man.Move(newFromUrl, newToUrl, out moveErr);
                    Debug.WriteLineIf(!r, moveErr);

                    needsRefresh = true;

                    tcs.SetResult(r);
                } catch (Exception ex) {
                    Debug.WriteLine(ex);
                    tcs.SetResult(false);
                }
            });
            if (coordErr != null)
            {
                tcs.TrySetResult(false);
            }

            return(tcs.Task);
        }
Exemplo n.º 5
0
        // Used for debuggin purposes
        internal static void SaveToFile(string fileName, CGBitmapContext bitmap)
        {
            if (bitmap == null)
            {
                throw new ObjectDisposedException("cgimage");
            }

            // With MonoTouch we can use UTType from CoreMobileServices but since
            // MonoMac does not have that yet (or at least can not find it) I will
            // use the string version of those for now.  I did not want to add another
            // #if #else in here.

            // for now we will just default this to png
            var typeIdentifier = "public.png";

            // * NOTE * we only support one image for right now.
            //NSMutableData imgData = new NSMutableData();
            NSUrl url = NSUrl.FromFilename(fileName);

            // Create an image destination that saves into the imgData
            CGImageDestination dest = CGImageDestination.FromUrl(url, typeIdentifier, 1);

            // Add an image to the destination
            dest.AddImage(bitmap.GetImage(), null);

            // Finish the export
            bool success = dest.Close();

            //                        if (success == false)
            //                                Console.WriteLine("did not work");
            //                        else
            //                                Console.WriteLine("did work: " + path);

            dest.Dispose();
            dest = null;
        }
Exemplo n.º 6
0
        public override bool PerformDragOperation(NSDraggingInfo sender)
        {
            Console.WriteLine("Drag Delegate received 'PerformDragOperation' sender: {0}", sender);

            //It seems that browserView does not send this message when it is an internal move.
            //It does all the work by sending a moveitems message to the datasource,
            // but I return false here just to be safe.

            NSObject obj = sender.DraggingSource;

            if (obj != null && obj.Equals(outlineView))
            {
                Console.WriteLine("\tLet the image browser handle it.");
                return(false);
            }

            NSPasteboard pb   = sender.DraggingPasteboard;
            NSArray      data = null;

            if (pb.Types.Contains(NSPasteboard.NSFilenamesType))
            {
                data = pb.GetPropertyListForType(NSPasteboard.NSFilenamesType) as NSArray;
            }
            if (data != null)
            {
                for (int i = 0; i < data.Count; i++)
                {
                    string path = (string)NSString.FromHandle(data.ValueAt((uint)i));
                    Console.WriteLine("From pasteboard Item {0} = {1}", i, path);
                    ((TreeDataSource)outlineView.DataSource).Directories.Add(
                        new Directory(NSUrl.FromFilename(path).AbsoluteString));
                    outlineView.ReloadData();
                }
            }
            return(true);
        }
Exemplo n.º 7
0
        static Task PlatformOpenAsync(OpenFileRequest request)
        {
            var fileUrl = NSUrl.FromFilename(request.File.FullPath);

            var documentController = UIDocumentInteractionController.FromUrl(fileUrl);

            documentController.Uti = request.File.ContentType;

            var vc = Platform.GetCurrentViewController();

            CoreGraphics.CGRect?rect = null;
            if (DeviceInfo.Idiom == DeviceIdiom.Tablet)
            {
                rect = new CoreGraphics.CGRect(new CoreGraphics.CGPoint(vc.View.Bounds.Width / 2, vc.View.Bounds.Height), CoreGraphics.CGRect.Empty.Size);
            }
            else
            {
                rect = vc.View.Bounds;
            }

            documentController.PresentOpenInMenu(rect.Value, vc.View, true);

            return(Task.CompletedTask);
        }
Exemplo n.º 8
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //Button Events
            playMovieButton.TouchUpInside += delegate
            {
                try
                {
                    //Set already instantiated MPMoviePlayerController to playback from Movies/file.m4v
                    mp = new MPMoviePlayerController(NSUrl.FromFilename("Movies/file.m4v"));

                    //enable AirPlay
                    mp.AllowsAirPlay = true;

                    //Add the MPMoviePlayerController View
                    this.View.AddSubview(mp.View);

                    //set the view to be full screen and show animated
                    mp.SetFullscreen(true, true);

                    //Disable the pinch-to-zoom gesture
                    mp.ControlStyle = MPMovieControlStyle.Fullscreen;

                    //MPMoviePlayer must be set to PrepareToPlay before playback
                    mp.PrepareToPlay();

                    //Play Movie
                    mp.Play();
                }
                catch
                {
                    Console.WriteLine("There was a problem playing back Video");
                }
            };
        }
Exemplo n.º 9
0
            private void RequestAvAssetHandler(AVAsset asset, AVAudioMix audioMix, NSDictionary info)
            {
                var videoUrl = (asset as AVUrlAsset).Url;
                //var temp3 = NSData.FromFile (videoUrl.AbsoluteString);
                var temp4 = NSData.FromUrl(videoUrl);

                string [] paths        = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User);
                string    downloadPath = paths [0];
                var       filePath     = Path.Combine(downloadPath, Path.GetFileName(videoUrl.AbsoluteString));
                NSError   error;
                bool      saveResult = temp4.Save(filePath, NSDataWritingOptions.Atomic, out error);

                if (saveResult)
                {
                    Debug.WriteLine("Save Success");
                    var    url      = NSUrl.FromFilename(filePath);
                    var    avAsset  = AVAsset.FromUrl(url);
                    CMTime duration = asset.Duration;
                }
                else
                {
                    Debug.WriteLine(error);
                }
            }
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            using (var context = new ModalDialogContext())
            {
                var panel = new NSOpenPanel();
                panel.CanChooseFiles          = false;
                panel.CanChooseDirectories    = true;
                panel.AllowsMultipleSelection = false;
                panel.ResolvesAliases         = true;
                panel.Title = Description ?? String.Empty;
                if (!String.IsNullOrWhiteSpace(SelectedPath) && System.IO.Directory.Exists(SelectedPath) && IsSubfolderOf(SelectedPath, RootFolder))
                {
                    panel.DirectoryUrl = NSUrl.FromFilename(SelectedPath);
                }

                if (NSPanelButtonType.Ok != (NSPanelButtonType)(int)panel.RunModal())
                {
                    return(false);
                }

                SelectedPath = panel.Url.Path;
                return(true);
            }
        }
Exemplo n.º 11
0
        public OperationResult DisplaySharingSheet(string text, string description, string filePath = "")
        {
            var items = new List <NSObject>()
            {
                new NSString(text)
            };

            if (!string.IsNullOrEmpty(description))
            {
                items.Add(new NSString(description));
            }

            if (!string.IsNullOrEmpty(filePath))
            {
                var url = NSUrl.FromFilename(filePath);
                items.Add(url);
            }

            var controller       = new UIActivityViewController(items.ToArray(), null);
            var parentController = NavigationHelper.GetActiveViewController();

            parentController.PresentViewController(controller, true, null);
            return(OperationResult.AsSuccess());
        }
Exemplo n.º 12
0
        private void ShowExtraMenu()
        {
            var sheet = MonoTouch.Utilities.GetSheet(Title);

            var openButton  = sheet.AddButton("Open In".t());
            var shareButton = ViewModel.HtmlUrl != null?sheet.AddButton("Share".t()) : -1;

            var showButton = ViewModel.HtmlUrl != null?sheet.AddButton("Show in Bitbucket".t()) : -1;

            var cancelButton = sheet.AddButton("Cancel".t());

            sheet.CancelButtonIndex = cancelButton;
            sheet.DismissWithClickedButtonIndex(cancelButton, true);
            sheet.Clicked += (s, e) => {
                if (e.ButtonIndex == openButton)
                {
                    var ctrl = new UIDocumentInteractionController();
                    ctrl.Url = NSUrl.FromFilename(ViewModel.FilePath);
                    ctrl.PresentOpenInMenu(NavigationItem.RightBarButtonItem, true);
                }
                else if (e.ButtonIndex == shareButton)
                {
                    var          item                  = UIActivity.FromObject(ViewModel.HtmlUrl);
                    var          activityItems         = new NSObject[] { item };
                    UIActivity[] applicationActivities = null;
                    var          activityController    = new UIActivityViewController(activityItems, applicationActivities);
                    PresentViewController(activityController, true, null);
                }
                else if (e.ButtonIndex == showButton)
                {
                    ViewModel.GoToHtmlUrlCommand.Execute(null);
                }
            };

            sheet.ShowInView(this.View);
        }
Exemplo n.º 13
0
        //NOTE: Must be called on UI Thread
        public void Show(string title, string message, byte[] imageData)
        {
            if (!NSThread.Current.IsMainThread)
            {
#if DEBUG
                throw new ThreadStateException("ShareImageService must be main-thread");
#else
                return;
#endif
            }

            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                    "screenshot.png");
            using (var stream = new FileStream(path, FileMode.Create))
            {
                stream.Write(imageData, 0, imageData.Length);
            }

            var items = new[] { NSObject.FromObject(title), NSUrl.FromFilename(path) };
            var activityController = new UIActivityViewController(items, null);
            var vc = GetVisibleViewController();

            vc.PresentViewController(activityController, true, null);
        }
Exemplo n.º 14
0
        public override bool PerformDragOperation(NSDraggingInfo sender)
        {
            NSPasteboard pb   = sender.DraggingPasteboard;
            NSArray      data = null;

            if (pb.Types.Contains(NSPasteboard.NSFilenamesType))
            {
                data = pb.GetPropertyListForType(NSPasteboard.NSFilenamesType) as NSArray;
            }
            if (data != null)
            {
                for (int i = 0; i < data.Count; i++)
                {
                    string path = (string)NSString.FromHandle(data.ValueAt((uint)i));
                    Console.WriteLine("From pasteboard Item {0} = {1}", i, path);
                    var outlineView = Subviews [0].Subviews [0] as NSOutlineView;
                    ((TreeDataSource)outlineView.DataSource).Directories.Add(
                        new Directory(NSUrl.FromFilename(path).AbsoluteString));
                    outlineView.ReloadData();
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 15
0
 private void SetContentUrl()
 {
     _contentSet = false;
     if (_moviePlayer != null && Path != null)
     {
         try
         {
             string path = IOContext.Current.TranslateLocalPath(Path);
             if (File.Exists(path))
             {
                 _moviePlayer.ContentUrl = NSUrl.FromFilename(path);
                 _contentSet             = true;
             }
             else
             {
                 throw new NonFatalException(D.FILE_NOT_EXISTS);
             }
         }
         catch (Exception e)
         {
             CurrentContext.HandleException(e);
         }
     }
 }
Exemplo n.º 16
0
        private void ShowExtraMenu()
        {
            var sheet       = new UIActionSheet();
            var openButton  = sheet.AddButton("Open In");
            var shareButton = ViewModel.HtmlUrl != null?sheet.AddButton("Share") : -1;

            var showButton = ViewModel.HtmlUrl != null?sheet.AddButton("Show in Bitbucket") : -1;

            var cancelButton = sheet.AddButton("Cancel");

            sheet.CancelButtonIndex = cancelButton;
            sheet.DismissWithClickedButtonIndex(cancelButton, true);
            sheet.Dismissed += (s, e) => {
                BeginInvokeOnMainThread(() =>
                {
                    if (e.ButtonIndex == openButton)
                    {
                        var ctrl = new UIDocumentInteractionController();
                        ctrl.Url = NSUrl.FromFilename(ViewModel.FilePath);
                        ctrl.PresentOpenInMenu(NavigationItem.RightBarButtonItem, true);
                    }
                    else if (e.ButtonIndex == shareButton)
                    {
                        Mvx.Resolve <IShareService>().ShareUrl(ViewModel.HtmlUrl);
                    }
                    else if (e.ButtonIndex == showButton)
                    {
                        ViewModel.GoToHtmlUrlCommand.Execute(null);
                    }
                });

                sheet.Dispose();
            };

            sheet.ShowFrom(NavigationItem.RightBarButtonItem, true);
        }
Exemplo n.º 17
0
        public static void StartRecording(string FileName)
        {
            NSObject[] values = new NSObject[]
            {
                NSNumber.FromFloat(44100.0f),
                NSNumber.FromInt32((int)AudioFormatType.LinearPCM),
                NSNumber.FromInt32(1),
                NSNumber.FromInt32((int)AVAudioQuality.High)
            };

            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVEncoderAudioQualityKey
            };

            NSDictionary settings = NSDictionary.FromObjectsAndKeys(values, keys);
            NSUrl        url      = NSUrl.FromFilename(FileName);

            // Set recorder parameters
            NSError error;

            _recorder = AVAudioRecorder.ToUrl(url, settings, out error);
            if (_recorder == null)
            {
                Console.WriteLine(error);
                return;
            }

            // Set Metering Enabled so you can get the time of the wav file
            _recorder.MeteringEnabled = true;
            _recorder.PrepareToRecord();
            _recorder.Record();
        }
Exemplo n.º 18
0
        public override void SetupSlide(PresentationViewController presentationViewController)
        {
            // Using a scene source allows us to retrieve the animations using their identifier
            var path        = NSBundle.MainBundle.PathForResource("Scenes/skinning/skinning", "dae");
            var sceneURL    = NSUrl.FromFilename(path);
            var sceneSource = SCNSceneSource.FromUrl(sceneURL, (NSDictionary)null);

            // Place the character in the scene
            var error = new NSError();
            var scene = sceneSource.SceneWithOption((SCNSceneLoadingOptions)null, out error);

            CharacterNode          = scene.RootNode.FindChildNode("avatar_attach", true);
            CharacterNode.Scale    = new SCNVector3(0.004f, 0.004f, 0.004f);
            CharacterNode.Position = new SCNVector3(5, 0, 12);
            CharacterNode.Rotation = new SCNVector4(0, 1, 0, -(float)(Math.PI / 8));
            CharacterNode.Hidden   = true;
            GroundNode.AddChildNode(CharacterNode);

            SkeletonNode = CharacterNode.FindChildNode("skeleton", true);

            // Prepare the other resources
            //TODO LoadGhostEffect ();
            ExtractAnimation(sceneSource);
        }
Exemplo n.º 19
0
        private void ShowExtraMenu()
        {
            var sheet        = CreateActionSheet(Title);
            var openButton   = !string.IsNullOrEmpty(ViewModel.FilePath) ? sheet.AddButton("Open In".t()) : -1;
            var shareButton  = !string.IsNullOrEmpty(ViewModel.HtmlUrl) ? sheet.AddButton("Share".t()) : -1;
            var showButton   = ViewModel.GoToHtmlUrlCommand.CanExecute(null) ? sheet.AddButton("Show in GitHub".t()) : -1;
            var cancelButton = sheet.AddButton("Cancel".t());

            sheet.CancelButtonIndex = cancelButton;
            sheet.DismissWithClickedButtonIndex(cancelButton, true);
            sheet.Clicked += (s, e) =>
            {
                try
                {
                    if (e.ButtonIndex == openButton)
                    {
                        var ctrl = new UIDocumentInteractionController();
                        ctrl.Url = NSUrl.FromFilename(ViewModel.FilePath);
                        ctrl.PresentOpenInMenu(NavigationItem.RightBarButtonItem, true);
                    }
                    else if (e.ButtonIndex == shareButton)
                    {
                        ViewModel.ShareCommand.Execute(null);
                    }
                    else if (e.ButtonIndex == showButton)
                    {
                        ViewModel.GoToHtmlUrlCommand.Execute(null);
                    }
                }
                catch
                {
                }
            };

            sheet.ShowInView(this.View);
        }
Exemplo n.º 20
0
        public bool Open(string fileName)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                return(false);
            }

            var url = NSUrl.FromFilename(fileName);

            if (url == null || !url.IsFileUrl)
            {
                return(false);
            }

            var viewer = UIDocumentInteractionController.FromUrl(url);
            var view   = Utils.GetTopView();

            viewer.PresentOpenInMenu(new RectangleF(0, -260, 320, 320), view, true);
            //if (!UIApplication.SharedApplication.CanOpenUrl(url))
            //    return false;

            //UIApplication.SharedApplication.OpenUrl(url);
            return(true);
        }
        public bool CreateMediaItem(LibraryItem libraryItem, bool updateMetadata)
        {
            try
            {
                using (AVAsset asset = AVAsset.FromUrl(NSUrl.FromFilename(libraryItem.LocalFilePath)))
                {
                    if (isRecording(asset))
                    {
                        if (updateMetadata)
                        {
                            fetchMetadata(asset, ref libraryItem);
                        }

                        lock (databaseSync)
                        {
                            using (var conn = new SQLiteConnection(DatabasePath))
                            {
                                LibraryItemProperties dbItem = null;

                                if (libraryItem.Storage == LibraryItemStorage.AppLocal)
                                {
                                    string relativePath = libraryItem.LocalFilePath.Substring(ItemDownloader.DownloaderPath.Length);
                                    dbItem = conn.Table <LibraryItemProperties>().FirstOrDefault(item => (relativePath == item.Path) && (libraryItem.Storage == item.Storage));
                                }
                                else if (libraryItem.Storage == LibraryItemStorage.iTunes)
                                {
                                    dbItem = conn.Table <LibraryItemProperties>().FirstOrDefault(item => (item.Id == libraryItem.ID) && (libraryItem.Storage == item.Storage));
                                }

                                if (dbItem != null)
                                {
                                    conn.Delete(dbItem);
                                }

                                LibraryItemProperties properties = new LibraryItemProperties()
                                {
                                    Id      = libraryItem.ID,
                                    Storage = libraryItem.Storage,
                                    Path    = (libraryItem.Storage == LibraryItemStorage.AppLocal) ? libraryItem.LocalFilePath.Substring(ItemDownloader.DownloaderPath.Length) : libraryItem.LocalFilePath
                                };

                                conn.Insert(properties);
                                return(true);
                            }
                        }
                    }
                    else
                    {
                        Logger.Log($"WARNNING: {libraryItem.LocalFilePath} is not a MMT recording with valid PLVF flag. DELETING");
                        NSError error;
                        if (!NSFileManager.DefaultManager.Remove(NSUrl.FromFilename(libraryItem.LocalFilePath), out error))
                        {
                            Logger.Log($"WARNNING: Unable to delete {libraryItem.LocalFilePath}: " + error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("ERROR: LocalLibrary.CreateMediaItem: " + ex);
            }

            return(false);
        }
Exemplo n.º 22
0
        private static async void OnOpenSampleFile(string path)
        {
#if WINDOWS_UWP
            var file = await StorageFile.GetFileFromPathAsync(path);

            await Launcher.LaunchFileAsync(file);
#elif __MACOS__
            if (!NSWorkspace.SharedWorkspace.OpenFile(path))
            {
                var alert = new NSAlert();
                alert.AddButton("OK");
                alert.MessageText     = "SkiaSharp";
                alert.InformativeText = "Unable to open file.";
                alert.RunSheetModal(NSApplication.SharedApplication.MainWindow);
            }
#elif __TVOS__
#elif __IOS__
            // the external / shared location
            var external = Path.Combine(Path.GetTempPath(), "SkiaSharpSample");
            if (!Directory.Exists(external))
            {
                Directory.CreateDirectory(external);
            }
            // copy file to external
            var newPath = Path.Combine(external, Path.GetFileName(path));
            File.Copy(path, newPath);
            // open the file
            var vc             = Xamarin.Forms.Platform.iOS.Platform.GetRenderer(Xamarin.Forms.Application.Current.MainPage) as UIViewController;
            var resourceToOpen = NSUrl.FromFilename(newPath);
            var controller     = UIDocumentInteractionController.FromUrl(resourceToOpen);
            if (!controller.PresentOpenInMenu(vc.View.Bounds, vc.View, true))
            {
                new UIAlertView("SkiaSharp", "Unable to open file.", (IUIAlertViewDelegate)null, "OK").Show();
            }
#elif __ANDROID__
            // the external / shared location
            var external = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "SkiaSharpSample");
            if (!Directory.Exists(external))
            {
                Directory.CreateDirectory(external);
            }
            // copy file to external
            var newPath = Path.Combine(external, Path.GetFileName(path));
            File.Copy(path, newPath);
            // open the file
            var uri    = Android.Net.Uri.FromFile(new Java.IO.File(newPath));
            var intent = new Intent(Intent.ActionView, uri);
            intent.AddFlags(ActivityFlags.NewTask);
            Application.Context.StartActivity(intent);
#elif __DESKTOP__
            Process.Start(path);
#elif __TIZEN__
            var appControl = new AppControl
            {
                Operation = AppControlOperations.View,
                Uri       = "file://" + path
            };
            var matchedApplications = AppControl.GetMatchedApplicationIds(appControl);
            if (matchedApplications.Any())
            {
                AppControl.SendLaunchRequest(appControl);
            }
#endif
        }
        void UpdateSource()
        {
            if (Element.Source != null)
            {
                AVAsset asset = null;

                var uriSource = Element.Source as UriMediaSource;
                if (uriSource != null)
                {
                    if (uriSource.Uri.Scheme == "ms-appx")
                    {
                        if (uriSource.Uri.LocalPath.Length <= 1)
                        {
                            return;
                        }

                        // used for a file embedded in the application package
                        asset = AVAsset.FromUrl(NSUrl.FromFilename(uriSource.Uri.LocalPath.Substring(1)));
                    }
                    else if (uriSource.Uri.Scheme == "ms-appdata")
                    {
                        string filePath = Platform.ResolveMsAppDataUri(uriSource.Uri);

                        if (string.IsNullOrEmpty(filePath))
                        {
                            throw new ArgumentException("Invalid Uri", "Source");
                        }

                        asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath));
                    }
                    else
                    {
                        asset = AVUrlAsset.Create(NSUrl.FromString(uriSource.Uri.AbsoluteUri));
                    }
                }
                else
                {
                    var fileSource = Element.Source as FileMediaSource;
                    if (fileSource != null)
                    {
                        asset = AVAsset.FromUrl(NSUrl.FromFilename(fileSource.File));
                    }
                }

                var item = new AVPlayerItem(asset);
                RemoveStatusObserver();

                _statusObserver = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus);


                if (_avPlayerViewController.Player != null)
                {
                    _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(item);
                }
                else
                {
                    _avPlayerViewController.Player = new AVPlayer(item);
                    _rateObserver = (NSObject)_avPlayerViewController.Player.AddObserver("rate", NSKeyValueObservingOptions.New, ObserveRate);
                }

                if (Element.AutoPlay)
                {
                    Play();
                }
            }
            else
            {
                if (Element.CurrentState == MediaElementState.Playing || Element.CurrentState == MediaElementState.Buffering)
                {
                    _avPlayerViewController.Player.Pause();
                    Controller.CurrentState = MediaElementState.Stopped;
                }
            }
        }
Exemplo n.º 24
0
        private bool PrepareAudioRecording()
        {
            var audioSession = AVAudioSession.SharedInstance();
            var err          = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);

            if (err != null)
            {
                Console.WriteLine("audioSession: {0}", err);
                return(false);
            }

            err = audioSession.SetActive(true);

            if (err != null)
            {
                Console.WriteLine("audioSession: {0}", err);
                return(false);
            }

            NSObject[] values = new NSObject[]
            {
                NSNumber.FromFloat(44100.0f),
                NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.MPEG4AAC),
                NSNumber.FromInt32(1),
                NSNumber.FromInt32((int)AVAudioQuality.High)
            };

            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVEncoderAudioQualityKey
            };

            var settings = NSDictionary.FromObjectsAndKeys(values, keys);

            NSError error;
            var     _url = NSUrl.FromFilename(Constants.INITIAL_AUDIO_FILE_PATH);

            _audioRecorder = AVAudioRecorder.Create(_url, new AudioSettings(settings), out error);
            if ((_audioRecorder == null) || (error != null))
            {
                Console.WriteLine(error);
                return(false);
            }

            if (!_audioRecorder.PrepareToRecord())
            {
                _audioRecorder.Dispose();
                _audioRecorder = null;
                return(false);
            }

            _audioRecorder.FinishedRecording += delegate(object sender, AVStatusEventArgs e)
            {
                _audioRecorder.Dispose();
                _audioRecorder = null;
                Console.WriteLine("Done Recording (status: {0})", e.Status);
            };

            return(true);
        }
Exemplo n.º 25
0
 private void PlatformInitialize(string fileName)
 {
     this.PlatformInitialize(NSUrl.FromFilename(fileName));
 }
Exemplo n.º 26
0
 public override bool RegisterFontFromFile(string fontPath)
 {
     return(CTFontManager.RegisterFontsForUrl(NSUrl.FromFilename(fontPath), CTFontManagerScope.Process) == null);
 }
        void LoadFontFile(string fileName)
        {
            CTFont nativeFont;
            var    dpiSize = 0;
            var    ext     = Path.GetExtension(fileName);

            if (!String.IsNullOrEmpty(ext))
            {
                if (nativeFontDescriptors == null)
                {
                    nativeFontDescriptors = new Dictionary <string, CTFontDescriptor> ();
                }

                //Try loading from Bundle first
                var fontName        = fileName.Substring(0, fileName.Length - ext.Length);
                var pathForResource = NSBundle.MainBundle.PathForResource(fontName, ext.Substring(1));

                NSUrl url;

                if (!string.IsNullOrEmpty(pathForResource))
                {
                    url = NSUrl.FromFilename(pathForResource);
                }
                else
                {
                    url = NSUrl.FromFilename(fileName);
                }

                // We will not use CTFontManager.RegisterFontsForUrl (url, CTFontManagerScope.Process);
                // here.  The reason is that there is no way we can be sure that the font can be created to
                // to identify the family name afterwards.  So instead we will create a CGFont from a data provider.
                // create CTFont to obtain the CTFontDescriptor, store family name and font descriptor to be accessed
                // later.
                try {
                    var dataProvider = new CGDataProvider(url.Path);
                    var cgFont       = CGFont.CreateFromProvider(dataProvider);

                    try {
                        nativeFont = new CTFont(cgFont, dpiSize, null);
                        if (!nativeFontDescriptors.ContainsKey(nativeFont.FamilyName))
                        {
                            nativeFontDescriptors.Add(nativeFont.FamilyName, nativeFont.GetFontDescriptor());
                            NSError error;
                            var     registered = CTFontManager.RegisterGraphicsFont(cgFont, out error);
                            if (!registered)
                            {
                                // If the error code is 105 then the font we are trying to register is already registered
                                // We will not report this as an error.
                                if (error.Code != 105)
                                {
                                    throw new ArgumentException("Error registering: " + Path.GetFileName(fileName));
                                }
                            }
                        }
                    }
                    catch
                    {
                        // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file
                        throw new System.IO.FileNotFoundException(fileName);
                    }
                }
                catch (Exception)
                {
                    // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file
                    throw new System.IO.FileNotFoundException(fileName);
                }
            }
        }
Exemplo n.º 28
0
        public override async Task <bool> PrepareData(PlaybackData data, bool isPlaying)
        {
            playbackData = data;
            stateObserver?.Dispose();
            stateObserver = null;
            CurrentSongId = data.SongId;
            AVPlayerItem playerItem       = null;
            var          songPlaybackData = data.SongPlaybackData;

            if (songPlaybackData.IsLocal || songPlaybackData.CurrentTrack.ServiceType == MusicPlayer.Api.ServiceType.iPod)
            {
                if (songPlaybackData.Uri == null)
                {
                    return(false);
                }
                var url = string.IsNullOrWhiteSpace(songPlaybackData?.CurrentTrack?.FileLocation) ? new NSUrl(songPlaybackData.Uri.AbsoluteUri) : NSUrl.FromFilename(songPlaybackData.CurrentTrack.FileLocation);
                playerItem = AVPlayerItem.FromUrl(url);
                await playerItem.WaitStatus();
            }
            else
            {
#if HttpPlayback
                var urlEndodedSongId = HttpUtility.UrlEncode(data.SongId);
                var url = $"http://localhost:{LocalWebServer.Shared.Port}/api/GetMediaStream/Playback?SongId={urlEndodedSongId}";
                playerItem = AVPlayerItem.FromUrl(new NSUrl(url));
#else
                NSUrlComponents comp =
                    new NSUrlComponents(
                        NSUrl.FromString(
                            $"http://localhost/{songPlaybackData.CurrentTrack.Id}.{data.SongPlaybackData.CurrentTrack.FileExtension}"), false);
                comp.Scheme = "streaming";
                if (comp.Url != null)
                {
                    var asset = new AVUrlAsset(comp.Url, new NSDictionary());
                    asset.ResourceLoader.SetDelegate(resourceDelegate, DispatchQueue.MainQueue);
                    playerItem    = new AVPlayerItem(asset, (NSString)"duration");
                    stateObserver = playerItem.AddObserver("status", NSKeyValueObservingOptions.New, (obj) =>
                    {
                        if (shouldBePlaying)
                        {
                            player.Play();
                        }
                        Console.WriteLine($"Player Status {playerItem.Status}");
                    });
                }
#endif
            }
            player.ReplaceCurrentItemWithPlayerItem(playerItem);
            IsPrepared = true;

            return(true);
        }
Exemplo n.º 29
0
 void AudioPlayer.PlayAudio()
 {
     Player = new AVAudioPlayer(NSUrl.FromFilename(Path.Combine(AudioFilePath, AudioFileName + ".wav")), ".wav", out Error);
     Player.Play();
 }
Exemplo n.º 30
0
        public void OpenPDF(string filename)
        {
            var viewer = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filename));

            viewer.PresentOpenInMenu(new RectangleF(0, -260, 320, 320), GetVisibleViewController().View, true);
        }