How can I trim mp3 file in UWP - c#

I want to trim a music file(mp3) in my UWP win 10 app. I try using Naudio but it's not working in my app, so how can i do it ?
Anyone any ideas?

If you want to trim a mp3 file, you can use Windows.Media.Editing namespace, especially MediaClip class.
By default, this class is used for clipping from a video file. But we can also use this class to trim mp3 file by setting MediaEncodingProfile in MediaComposition.RenderToFileAsync method while rendering.
Following is a simple sample:
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
openPicker.FileTypeFilter.Add(".mp3");
var pickedFile = await openPicker.PickSingleFileAsync();
if (pickedFile != null)
{
//Created encoding profile based on the picked file
var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(pickedFile);
var clip = await MediaClip.CreateFromFileAsync(pickedFile);
// Trim the front and back 25% from the clip
clip.TrimTimeFromStart = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
clip.TrimTimeFromEnd = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
var composition = new MediaComposition();
composition.Clips.Add(clip);
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
savePicker.FileTypeChoices.Add("MP3 files", new List<string>() { ".mp3" });
savePicker.SuggestedFileName = "TrimmedClip.mp3";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
//Save to file using original encoding profile
var result = await composition.RenderToFileAsync(file, MediaTrimmingPreference.Precise, encodingProfile);
if (result != Windows.Media.Transcoding.TranscodeFailureReason.None)
{
System.Diagnostics.Debug.WriteLine("Saving was unsuccessful");
}
else
{
System.Diagnostics.Debug.WriteLine("Trimmed clip saved to file");
}
}
}

Related

Saving Canvas to device memory in Xamarin.Forms

I have canvas made from bitMap (photo) and my finger drawings in Xamarin Forms. I need to save it to memory device (perfectly it would be photo roll but could be just memory of device). For now (after googling few hours) i have something like this:
saveButt.Clicked += async(sender, args) =>
{
var newSurface = SKSurface.Create(
(int)canvasView.CanvasSize.Width,
(int)canvasView.CanvasSize.Height,
SKImageInfo.PlatformColorType,
SKAlphaType.Premul);
var canvas = newSurface.Canvas;
if (photoBitmap != null)
{
canvas.DrawBitmap(photoBitmap, new SKRect(0, 0, (float) canvasView.Width, (float) canvasView.Height));
}
foreach (SKPath path in completedPaths)
{
canvas.DrawPath(path, paint);
}
foreach (SKPath path in inProgressPaths.Values)
{
canvas.DrawPath(path, paint);
}
canvas.Flush();
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
};
I don't know how i can get access to memory or photo roll to save it.
#Edit
I tried use PCLStorage plugin to save it and for now it don't throw any exceptions or errors but still when i look through all folders i can't find any new folder or file with those names.
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("image.png",
CreationCollisionOption.ReplaceExisting);
using (Stream s = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
{
pngImage.SaveTo(s);
}

Xamarin.forms how I can add ability to take photo or select it from Gallery

I am Using Xamarin.Forms, how I can add ability to take photo or select it from Gallery.
I Find a lot of solutions, but no one of them is completed.
the Xamarin Forms Media plugin will do this, and includes sample code
takePhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.PhotosSupported)
{
DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Media.Plugin.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
if (file == null)
return;
DisplayAlert("File Location", file.Path, "OK");
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
};
This can now be easily achieved using Xamarin Essentials MediaPicker.
Here is the link to the docs and sample code for Android, iOS and UWP..
https://learn.microsoft.com/en-us/xamarin/essentials/media-picker?tabs=android
var profile = new Image { };
profile.Source = "profile.png";
profile.HorizontalOptions = LayoutOptions.StartAndExpand;
profile.VerticalOptions = LayoutOptions.StartAndExpand;
var profiletap = new TapGestureRecognizer();
profiletap.Tapped += async (s, e) =>
{
var file = await CrossMedia.Current.PickPhotoAsync();
if (file == null)
return;
await DisplayAlert("File Location", file.Path, "OK");
im = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
//file.Dispose();
return stream;
});
profile.Source = im;
// await Navigation.PushModalAsync(new PhotoPage(im));
};
profile.GestureRecognizers.Add(profiletap);

save a xml file with c# in Universal app

I've this Xml :
<?xml version="1.0" encoding="utf-8" ?>
<GirlsTimes>
<Angie>00:00:00</Angie>
...
<Nicole>00:00:00</Nicole>
</GirlsTimes>
I've a textbox when you can put a time in format "hh:mm:ss" (TBAngie).
When the focus on this textbox was lost, I want to save the new value in the same Xml file :
private async void TBAngie_LostFocus(object sender, RoutedEventArgs e)
{
try
{
if (!checkContent(TBAngie.Text))
{
TBAngie.Text = string.Empty;
var dialog = new MessageDialog("Veuillez encodez un temps hh:mm:ss svp.");
await dialog.ShowAsync();
}
else
{
StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
string repMaxXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "XML/GirlsTimes.xml");
loadedData = XDocument.Load(repMaxXMLPath);
var items = from item in loadedData.Descendants("GirlsTimes")
where item.Element("Angie").Value != TBAngie.Text
select item;
foreach (XElement itemElement in items)
{
itemElement.SetElementValue("Angie", TBAngie.Text);
}
loadedData.Save(xw);
}
}
}
catch (Exception ex)
{
var dialog = new MessageDialog(ex.Message);
await dialog.ShowAsync();
}
}
Apparently the <Angie> node value was update well (I see the updated node in debug mode), but when I refresh the page (quit the current page and reload it), the value was not update. So I think my method to save the new xml was not good but I don't know why...
What I made wrong ? Thanks in advance.
EDIT
Just before loadedData.Save() I've made a .toString() and I've this :
<GirlsTimes>
<Angie>00:12:34</Angie>
...
<Nicole>00:00:00</Nicole>
</GirlsTimes>
The app's install directory is a read-only location. If you need to change file contents, copy it to Windows.Storage.ApplicationData.Current.LocalFolder. So, when your app loads the file, try the LocalFolder location first, if no file is there, read it from InstalledLocation.
Refer to this article for details.
Wouaouhhh, after many searchs and try, I've the solution :
This is my read method (I Know isn't the right way to use try/catch/finally...)) :
private async void GetGirlsTimes()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
try
{
StorageFile textFile = await localFolder.GetFileAsync("GirlsTimes.xml");
using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
{
Stream s = textStream.AsStreamForRead();
loadedData = XDocument.Load(s);
}
}
catch
{
storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("AppData");
storageFile = await storageFolder.GetFileAsync("GirlsTimes.xml");
using (IRandomAccessStream writeStream = await storageFile.OpenAsync(FileAccessMode.Read))
{
Stream s = writeStream.AsStreamForRead();
loadedData = XDocument.Load(s);
}
}
finally
{
...//put the value from loadedData to my differents TextBoxes.
}
}
And this is My Write Method :
var items = from item in loadedData.Descendants("GirlsTimes")
where item.Element("Angie").Name == "Angie"
select item;
foreach (XElement itemElement in items)
{
itemElement.SetElementValue("Angie", TBAngie.Text);
}
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textFile = await localFolder.CreateFileAsync("GirlsTimes.xml", CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (DataWriter textWriter = new DataWriter(textStream))
{
textWriter.WriteString(loadedData.ToString());
await textWriter.StoreAsync();
}
}
And then I can write/read/update my Xml. Thanks For the help. I Valid Your Answer Nox Noctis :)

Convert StorageFile to WriteableBitmap WP8.1 Silverlight

I am developing this application where I am able to get all the pictures from picture library as StorageFile data type. now I want to change it to writeablebitmap, apply a sketch filter and show in image control. can someone please help me in changing the data type from StorageFile to writeablebitmap?
here is my code:
StorageFolderpicturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageFile> file = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(file.Count > 0)
{
foreach(StorageFile f in file)
{
// the code for changing the data type will go here
}
This code works for me.
if (file.Count > 0)
{
foreach (StorageFile f in file)
{
ImageProperties properties = await f.Properties.GetImagePropertiesAsync();
WriteableBitmap bmp = new WriteableBitmap((int)properties.Width, (int)properties.Height);
bmp.SetSource((await f.OpenReadAsync()).AsStream());
// Ready to go with bmp
}
}
Try this, it should work:
IReadOnlyList<IStorageFile> files = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(files.Count > 0)
{
var images = new List<WriteableBitmap>();
foreach(var f in files)
{
var bitmap = new WriteableBitmap(500, 500);
using (var stream = await f.OpenAsync(FileAccessMode.ReadWrite))
{
bitmap.SetSource(stream);
}
images.Add(bitmap);
}
}

How Get ALL photos with out filepicker

I m make a simple window phone 8.1 app i want to get aLl photos to display in app and then user select PickMultipleFilesAndContinue ..... but im dont know how to do it . i made this code openfiler picker taking me to phone library ..... Is there any other way to get photos in windows phone 8.1 ?
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
openPicker.PickMultipleFilesAndContinue();
view.Activated += view_Activated;
}
private async void view_Activated(CoreApplicationView sender, Windows.ApplicationModel.Activation.IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
bitmapImages = new ObservableCollection<BitmapImage>();
IReadOnlyList<StorageFile> files = args.Files;
if (files.Count > 0)
{
StringBuilder output = new StringBuilder("Picked files:\n");
// Application now has read/write access to the picked file(s)
foreach (StorageFile file in files)
{
output.Append(file.Name + "\n");
using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
try
{
BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
bitmapImage.DecodePixelHeight = 200;
bitmapImage.SetSource(stream);
bitmapImages.Add(bitmapImage);
}
catch (ArgumentException Ex)
{
Debug.WriteLine("Exception ", Ex.Message);
}
}
}
ImageCollection.ItemsSource = bitmapImages;
OutputTextBlock.Text = output.ToString();
}
else
{
OutputTextBlock.Text = "Operation cancelled.";
}
}
by this im geting only selected photos . i want all to display and then user select from them .....
You can access the photos programmatically and then add them to your ImageCollection. I've resized the photos, because otherwise the App crashes on my phone.
StorageFolder pictureFolder = KnownFolders.PicturesLibrary; //or another folder
IReadOnlyList<IStorageItem> nameList = await pictureFolder.GetItemsAsync();
var bitmapImages = new ObservableCollection<BitmapImage>();
foreach (var item in nameList)
{
if (item is StorageFile)
{
if (item.Name.Substring(item.Name.Length - 4, 3).ToLower() == "jpeg" || item.Name.Substring(item.Name.Length - 3, 3).ToLower() == "jpg" || item.Name.Substring(item.Name.Length - 3, 3).ToLower() == "png")
{
Image image = new Image();
StorageFile file = await pictureFolder.GetFileAsync(item.Name);
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
if (bitmapImage.DecodePixelHeight >= bitmapImage.DecodePixelWidth)
{
bitmapImage.DecodePixelWidth = bitmapImage.DecodePixelHeight / 100;
bitmapImage.DecodePixelHeight = 100;
}
else
{
bitmapImage.DecodePixelHeight = bitmapImage.DecodePixelWidth / 100;
bitmapImage.DecodePixelWidth = 100;
}
bitmapImages.Add(bitmapImage);
}
}
}

Categories

Resources