/// <summary> /// Obtains the list of folders that make up the Pictures library and binds the FoldersListView /// to this list. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ListFoldersButton_Click(object sender, RoutedEventArgs e) { ListFoldersButton.IsEnabled = false; picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); // Bind the FoldersListView to the list of folders that make up the library FoldersListView.ItemsSource = picturesLibrary.Folders; // Register for the DefinitionChanged event to be notified if other apps modify the library picturesLibrary.DefinitionChanged += async(StorageLibrary innerSender, object innerEvent) => { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { UpdateHeaderText(); }); }; UpdateHeaderText(); }
public ImageViewerPage() { InitializeComponent(); DataTransferManager.GetForCurrentView().DataRequested += (s, e) => { e.Request.Data.Properties.Title = "分享自iV2EX"; e.Request.Data.SetText(_imageUrl); e.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(_file)); }; var share = Observable.FromEventPattern <RoutedEventArgs>(ShareImage, nameof(ShareImage.Click)) .ObserveOnCoreDispatcher() .Subscribe(x => { if (DataTransferManager.IsSupported()) { DataTransferManager.ShowShareUI(); } }); var save = Observable.FromEventPattern <RoutedEventArgs>(SaveImage, nameof(SaveImage.Click)) .ObserveOnCoreDispatcher() .Subscribe(async x => { try { var library = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); var path = await library.SaveFolder.CreateFolderAsync("iV2EX", CreationCollisionOption.OpenIfExists); await _file.CopyAsync(path, _file.Name + Path.GetExtension(_imageUrl), NameCollisionOption.ReplaceExisting); ToastTips.ShowTips("已经保存到图片库"); } catch { ToastTips.ShowTips("保存失败"); } }); var menu = Observable.FromEventPattern <TappedRoutedEventArgs>(MenuItemPanel, nameof(MenuItemPanel.Tapped)) .ObserveOnCoreDispatcher() .Subscribe(x => MenuItemPanel.ContextFlyout.ShowAt(MenuItemPanel)); _events = new List <IDisposable> { share, save, menu }; }
/// <summary> /// 加载picture library中前9张图片 /// </summary> private async void LoadImages() { WaitingRing.IsActive = true; var pictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); if (pictures != null) { var folder = pictures.SaveFolder; StorageFileQueryResult query = folder.CreateFileQuery(Windows.Storage.Search.CommonFileQuery.OrderByDate); var images = await query.GetFilesAsync(); if (images != null) { if (images.Count > 9) //只显示最前面的9张 { images = images.Take(9).ToList(); } images.ToList().ForEach(async(image) => { try { BitmapImage img = new BitmapImage(); var f = await image.OpenAsync(FileAccessMode.Read); if (f != null) { f.Seek(0); await img.SetSourceAsync(f); Images.Add(img); _cache.Add(img, image); } } catch { } }); } } if (Images.Count == 0) { WaitingRing.Visibility = Visibility.Visible; } WaitingRing.IsActive = false; }
private async Task <StorageFile> GetPhotoFromPreviewFrame() { var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; var videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height); var frame = await _mediaCapture.GetPreviewFrameAsync(videoFrame); SoftwareBitmap frameBitmap = frame.SoftwareBitmap; WriteableBitmap bitmap = new WriteableBitmap(frameBitmap.PixelWidth, frameBitmap.PixelHeight); frameBitmap.CopyToBuffer(bitmap.PixelBuffer); var myPictures = await StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures); StorageFile file = await myPictures.SaveFolder.CreateFileAsync("_photo.jpg", CreationCollisionOption.ReplaceExisting); using (var captureStream = new InMemoryRandomAccessStream()) { using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await bitmap.ToStreamAsJpeg(captureStream); var decoder = await BitmapDecoder.CreateAsync(captureStream); var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder); var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) } }; await encoder.BitmapProperties.SetPropertiesAsync(properties); await encoder.FlushAsync(); } } // Close the frame frame.Dispose(); frame = null; return(file); }
private async void downLoad_Click(object sender, RoutedEventArgs e) { if (Uri.IsWellFormedUriString(source.Text, UriKind.Absolute)) { Uri uri = new Uri(source.Text); var myMusics = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); var myMusic = myMusics.SaveFolder; var fileName = Path.GetFileName(uri.LocalPath); try { StorageFile musicFile = await myMusic.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.FailIfExists); if (musicFile != null) { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); IBuffer buffer; try { buffer = await httpClient.GetBufferAsync(uri); } catch (Exception ex) { Tips.Text = "download fail!"; return; } await FileIO.WriteBufferAsync(musicFile, buffer); Tips.Text = "download complete!"; mediaPlayer.Source = MediaSource.CreateFromUri(new Uri(source.Text)); } } catch (Exception ex) { Tips.Text = "file exist"; mediaPlayer.Source = MediaSource.CreateFromUri(new Uri(source.Text)); } } else { Tips.Text = "Invalid url!"; } }
public async Task <Library> LoadLibrary() { string libraryPath = (string)ApplicationData.Current.LocalSettings.Values[LocalSettingLibraryPathKey]; StorageLibrary musicLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); StorageFolder libraryRoot = musicLibrary.Folders.FirstOrDefault(f => f.Path.Equals(libraryPath)); if (libraryRoot == null) { throw new InvalidOperationException("Couldn't find the user collection in the system music library"); } Library library = await Library.LoadAsync(libraryRoot); CurrentLibrary = library; LibraryLoaded?.Invoke(library); return(library); }
/// <summary> /// Handle adding folders. /// </summary> private async void AddFolderStub() { // Select a folder. var libraryFolders = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); var folder = await libraryFolders.RequestAddFolderAsync(); if (folder == null || LibraryFolders.Any((c) => c.Path == folder.Path)) { return; } // Add folder to library. LibraryFolders.Add(new FolderModel { Name = folder.Name, Path = folder.Path, RemoveFolderButtonClickedRelayCommand = _removeFolderButtonClickedRelayCommand }); }
public static async Task <StorageLibrary> TryAccessLibraryAsync(KnownLibraryId library) { try { return(await StorageLibrary.GetLibraryAsync(library)); } catch (UnauthorizedAccessException) { ContentDialog unauthorizedAccessDialog = new ContentDialog() { Title = "Unauthorized Access", Content = string.Format("\r\nTo access the {0} library, go to Settings and enable access. \r\nMake sure that changes has been saved.", library), PrimaryButtonText = "OK" }; await unauthorizedAccessDialog.ShowAsync(); } return(null); }
public async Task LoadInitialMusic() { StorageLibrary music = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); QueryOptions query = new QueryOptions(CommonFileQuery.OrderByDate, new string[] { ".mp3" }); query.FolderDepth = FolderDepth.Deep; var files = await KnownFolders.MusicLibrary.CreateFileQueryWithOptions(query).GetFilesAsync(); foreach (StorageFile file in files) { Songs.Add(new SongViewModel { FileHandle = file, Properties = await file.Properties.GetMusicPropertiesAsync() }); } }
private async Task Register() { BackgroundExecutionManager.RemoveAccess(); var promise = await BackgroundExecutionManager.RequestAccessAsync(); if (promise == BackgroundAccessStatus.DeniedByUser || promise == BackgroundAccessStatus.DeniedBySystemPolicy) { return; } foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == TaskName) { task.Value.Unregister(true); } } var builder = new BackgroundTaskBuilder(); builder.Name = TaskName; builder.TaskEntryPoint = EntryPoint; var library = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); var contentChangedTrigger = StorageLibraryContentChangedTrigger.Create(library); builder.SetTrigger(contentChangedTrigger); builder.IsNetworkRequested = true; builder.CancelOnConditionLoss = true; try { BackgroundTaskRegistration registration = builder.Register(); Debug.WriteLine(registration.Name); Debug.WriteLine(registration.TaskId); Debug.WriteLine(registration.Trigger); } catch (Exception e) { Debug.WriteLine(e.Message); throw; } }
public IAsyncAction SaveScreenshotAsync(SnapshotData data) { byte[] pixeldata = data.data; int pitch = data.pitch; Func <Task> helper = async() => { if (this.currentROM == null) { return; } int pixelWidth = pitch / 4; int pixelHeight = (int)pixeldata.Length / pitch; //IStorageFile file = await this.GetFileUsingExtension(".png", true); var lib = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); StorageFolder saveFolder = lib.SaveFolder; saveFolder = await saveFolder.CreateFolderAsync(Package.Current.DisplayName, CreationCollisionOption.OpenIfExists); String filename = String.Format( SCREENSHOT_NAME_TEMPLATE, (this.currentROM.File as StorageFile).DisplayName, DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss") ) + ".png"; StorageFile file = await saveFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore, (uint)pixelWidth, (uint)pixelHeight, 96.0, 96.0, pixeldata); await encoder.FlushAsync(); } }; return(helper().AsAsyncAction()); }
public async void getImgs() { //Images = null; var pictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); if (pictures != null) { var folder = pictures.SaveFolder; StorageFileQueryResult query = folder.CreateFileQuery(Windows.Storage.Search.CommonFileQuery.OrderByDate); var images = await query.GetFilesAsync(); if (images != null) { //if (images.Count > 9) //只显示最前面的9张 //{ // images = images.Take(9).ToList(); //} images.ToList().ForEach(async(image) => { try { BitmapImage img = new BitmapImage(); var f = await image.OpenAsync(FileAccessMode.Read); if (f != null) { f.Seek(0); await img.SetSourceAsync(f); Images.Add(img); _cache.Add(img, image); //imagesource_dict.Add(f); } } catch { } }); } images = images.ToList(); } }
private async void RemoveDataSource_Button_Click(object sender, RoutedEventArgs e) { var musicLib = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); var item = (DataSourceItem)DataSource_ListView.SelectedItem; bool isRemoved = await musicLib.RequestRemoveFolderAsync(await StorageFolder.GetFolderFromPathAsync(item.Name)); if (!isRemoved) { return; } DataSource_ListView.SelectedIndex -= 1; var list = _vm.DataSourceList.ToList(); list.Remove(item); _vm.DataSourceList = list; await Ioc.Default.GetRequiredService <MusicFileScanningService>().ScanAsync(); }
internal async Task StartRecordingAsync(string projectName, int sequenceNumber) { bool hasCameraName = _CameraNameText != null && _CameraNameText.Length > 0; string baseName = hasCameraName ? _CameraNameText : this.Name; bool hasProjectName = projectName != null && projectName.Length > 0; string project = hasProjectName ? projectName : "RecordCamsProject"; string name = project + "\\" + sequenceNumber.ToString("000") + "_" + baseName + ".mp4"; var myVideos = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos); savedVideoFile = await myVideos.SaveFolder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName); _mediaRecording = await mediaCapture.PrepareLowLagRecordToStorageFileAsync( MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p), savedVideoFile); mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded; await _mediaRecording.StartAsync(); }
//access the default music folder public async Task <Dictionary <string, object> > GetAlbumsAsync() { //To get a reference to the user's Music, Pictures, or Video library var myMusic = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); //get the List of folders in a library var myMusicFolders = myMusic.Folders; // dictionary takes Tkey = folder name, Tvalue = album object Dictionary <string, object> folderCollection = new Dictionary <string, object>(); //add the albums/folders to a dictionary foreach (var album in myMusicFolders) { folderCollection.Add(album.Name, album.Properties); } //get the default folder where new files will be saved //var defaultFolder = myMusic.SaveFolder; return(folderCollection); }
private async Task InitializeFileLoading() { var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); Const.ROOT_DIR = await myPictures.SaveFolder.GetFolderAsync("Camera Roll"); if (Const.LOAD_IMAGES) { // check input data at image directory _imageFiles = await GetImageFiles(Const.ROOT_DIR, Const.TEST_IMAGE_DIR_NAME); if (_imageFiles.LongCount() == 0) { UnityEngine.Debug.Log("test image directory empty!"); } else { UnityEngine.Debug.Log("Number of image files in the input folder: " + _imageFiles.LongCount()); } } }
private async void TakePhotoAsync() { var stream = new InMemoryRandomAccessStream();; Debug.WriteLine("Taking Photo..."); var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder; await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); try { var file = await _captureFolder.CreateFileAsync(imageFileName, CreationCollisionOption.ReplaceExisting); Debug.WriteLine("사진이 찍혔고, 다음 위치에 저장될 예정입니다 : " + file.Path); imagePath = file.Path; //XAML에서 사진 미리 보여주고 뒤이어 바로 사진저장 await CameraHelper.ReencodeAndSavePhotoAsync(stream, file); Debug.WriteLine("사진이 저장되었습니다"); ConfirmBtn.Visibility = Visibility.Visible; using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(fileStream); imageControl.Source = bitmapImage; } Debug.WriteLine("사진을 미리봅니다"); } catch (Exception ex) { Debug.WriteLine("사진을 찍는동안 문제가 발생하였습니다: " + ex.ToString()); } }
/// <summary> /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors /// </summary> /// <returns></returns> private async Task SetupUiAsync() { // Hide the status bar if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); } // Populate orientation variables with the current state _displayOrientation = _displayInformation.CurrentOrientation; if (_orientationSensor != null) { _deviceOrientation = _orientationSensor.GetCurrentOrientation(); } RegisterEventHandlers(); var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); // Fall back to the local app storage if the Pictures Library is not available _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder; }
private async void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { var d = args.GetDeferral(); var tasks = new List <Task <StorageFile> >(); StorageFolder folder; try { if (!Settings.Current.DownloadPathToken.IsNullorEmpty()) { folder = await Windows.Storage.AccessCache.StorageApplicationPermissions. FutureAccessList.GetFolderAsync(Settings.Current.DownloadPathToken); } else { var lib = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); folder = await lib.SaveFolder.CreateFolderAsync("Download", CreationCollisionOption.OpenIfExists); } } catch (Exception) { var lib = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); folder = await lib.SaveFolder.CreateFolderAsync("Download", CreationCollisionOption.OpenIfExists); } MainPage.Current.PopMessage(SmartFormat.Smart.Format("Starting download {0} {0:song|songs}", SongList.Count)); foreach (var item in SongList) { var t = Task.Run(async() => { var res = await FileTracker.DownloadMusic(item.Song, folder); await FileTracker.AddTags(res, item.Song); }); } d.Complete(); }
public static async Task GetAllMusicFolders() { try { #if WINDOWS_APP StorageLibrary musicLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); foreach (StorageFolder storageFolder in musicLibrary.Folders) { await CreateDatabaseFromMusicFolder(storageFolder); } #else StorageFolder musicLibrary = KnownFolders.MusicLibrary; LogHelper.Log("Searching for music from Phone MusicLibrary ..."); await CreateDatabaseFromMusicFolder(musicLibrary); #endif } catch (Exception e) { ExceptionHelper.CreateMemorizedException("MusicLibraryManagement.GetAllMusicFolders", e); } }
/// <summary> /// Handle folder removal. /// </summary> /// <param name="e">Param for removal operation.</param> private async void OnRemoveFolderButtonClicked(RoutedEventArgs e) { try { var ctx = (FolderModel)((Button)e.OriginalSource).DataContext; var libraryFolders = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); var folder = libraryFolders.Folders.SingleOrDefault((f) => f.Path == ctx.Path); if (folder == null) { return; } if (await libraryFolders.RequestRemoveFolderAsync(folder)) { LibraryFolders.Remove(ctx); } } catch (Exception ex) { TelemetryHelper.TrackExceptionAsync(ex); } }
internal async void SaveImage() { try { var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); var motionPictures = await myPictures.SaveFolder.CreateFolderAsync("MotionPictures", CreationCollisionOption.OpenIfExists); StorageFile file = await motionPictures.CreateFileAsync("motionPhoto.jpg", CreationCollisionOption.GenerateUniqueName); var stream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(MainPage.oldImg); await encoder.FlushAsync(); using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var decoder = await BitmapDecoder.CreateAsync(stream); var encoder1 = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder); var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) } }; await encoder1.BitmapProperties.SetPropertiesAsync(properties); await encoder1.FlushAsync(); } //ms.Dispose(); stream.Dispose(); } catch (Exception) { //throw; } }
async private void InitMediaCapture() { _mediaCapture = new MediaCapture(); var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back); var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id }; await _mediaCapture.InitializeAsync(settings); _displayRequest.RequestActive(); PreviewControl.Source = _mediaCapture; await _mediaCapture.StartPreviewAsync(); var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder; await Task.Delay(500); CaptureImage(); }
public async Task <ObservableCollection <BitmapImage> > getImgs() { var pictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); if (pictures != null) { var folder = pictures.SaveFolder; StorageFileQueryResult query = folder.CreateFileQuery(Windows.Storage.Search.CommonFileQuery.OrderByDate); var images = await query.GetFilesAsync(); if (images != null) { if (images.Count > 9) //只显示最前面的9张 { images = images.Take(9).ToList(); } images.ToList().ForEach(async(image) => { try { BitmapImage img = new BitmapImage(); var f = await image.OpenAsync(FileAccessMode.Read); if (f != null) { f.Seek(0); await img.SetSourceAsync(f); (img_tmp.Images).Add(img); _cache.Add(img, image); } } catch { } }); } } return(img_tmp.Images); }
//选择保存图片的文件夹 private async void button1_Click(object sender, RoutedEventArgs e) { if (shifou_jiazai == false) { return; } //选择文件夹 var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); StorageFolder newFolder = await myPictures.RequestAddFolderAsync(); //保存信息 if (newFolder != null) { daima.huancun.shezhi_Quanju.baocun_wenjianjia_lujing = newFolder.Path; daima.huancun.shezhi_Quanju.baocun_wenjianjia = newFolder.Name; await daima.huancun.shezhi_Quanju.BaocunAsync(); } //更新UI textbox1.Text = daima.huancun.shezhi_Quanju.baocun_wenjianjia_lujing; }
private static async Task <List <KeyValuePair <StorageLibraryChangeType, object> > > LoadLibrary() { List <KeyValuePair <StorageLibraryChangeType, object> > changes = new List <KeyValuePair <StorageLibraryChangeType, object> >(); try { QueryOptions queryOption = new QueryOptions (CommonFileQuery.OrderByTitle, new string[] { ".mp3", ".m4a", ".mp4" }); queryOption.FolderDepth = FolderDepth.Deep; Queue <IStorageFolder> folders = new Queue <IStorageFolder>(); IReadOnlyList <StorageFile> files = await KnownFolders.MusicLibrary.CreateFileQueryWithOptions (queryOption).GetFilesAsync(); foreach (StorageFile file in files) { changes.Add( new KeyValuePair <StorageLibraryChangeType, object>(StorageLibraryChangeType.MovedIntoLibrary, file) ); } StorageLibrary musicsLib = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); StorageLibraryChangeTracker musicTracker = musicsLib.ChangeTracker; musicTracker.Enable(); Debug.WriteLine("Get songs succeed"); return(changes); } catch (Exception e) { Debug.WriteLine(e.ToString()); return(changes); } }
private async void takeSnapBtn_Click(object sender, RoutedEventArgs e) { if (mediaCapture == null) { MessageDialog messageDialog = new MessageDialog("Please start camera"); await messageDialog.ShowAsync(); return; } using (mediaCapture) { var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures); StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName); using (var captureStream = new InMemoryRandomAccessStream()) { await mediaCapture.InitializeAsync(); await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream); using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var decoder = await BitmapDecoder.CreateAsync(captureStream); var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder); var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) } }; await encoder.BitmapProperties.SetPropertiesAsync(properties); await encoder.FlushAsync(); } } } }
private static async Task <bool> EnsureLibraryReferenceAsync() { if (m_musicLibrary == null) { m_musicLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); } try { if (IsAutoTrackingEnabled && m_libChangeReader == null) { m_libChangeTracker = m_musicLibrary.ChangeTracker; m_libChangeTracker.Enable(); m_libChangeReader = m_libChangeTracker.GetChangeReader(); } return(true); } catch (Exception ex) when((uint)ex.HResult == 0x80080222) { return(false); } }
/// <summary> /// 创建新的录播计划 /// </summary> /// <param name="identifier">标识名,每一个下载任务不应相同</param> /// <param name="playlistUri">直播文件的地址</param> /// <param name="startTime">开始录播的时间</param> /// <param name="recordSpan">录播时长</param> public static RecordSchedule CreateSchedule( string identifier, string playlistUri, DateTimeOffset startTime, TimeSpan recordSpan) { var key = EncodeIndentifier(identifier); // 这里直接同步运行以避免async传染 var video = Async.InvokeAndWait(async() => await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos)); object path = null; ApplicationData.Current.LocalSettings.Values.TryGetValue("RecordingPath", out path); var pathstr = path?.ToString(); var filepath = (string.IsNullOrWhiteSpace(pathstr) ? video.SaveFolder.Path : pathstr) + '\\' + identifier + ".ts"; var schedule = new RecordSchedule(key) { PlaylistUri = playlistUri, StartTime = startTime, ScheduleSpan = recordSpan, Status = ScheduleStatus.Scheduled, SavePath = filepath }; RecordScheduleMessager.Instance.Trigger(key, RecordScheduleMessageType.Created); return(schedule); }
private async void button_2_Click(object sender, RoutedEventArgs e) { Uri uri = new Uri("http://www.neu.edu.cn/indexsource/neusong.mp3"); var myMusics = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music); var myMusic = myMusics.SaveFolder; var fileName = Path.GetFileName(uri.LocalPath); try { StorageFile musicFile = await myMusic.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.FailIfExists); if (musicFile != null) { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); IBuffer buffer; try { buffer = await httpClient.GetBufferAsync(uri); } catch (Exception ex) { text.Text = "download fail"; return; } await FileIO.WriteBufferAsync(musicFile, buffer); text.Text = "download complete"; } } catch (Exception ex) { text.Text = "file exist"; } }