I'm trying to create a Video with an Image using MediaTranscoder class in WindowsPhone 8.1 SDK. If I succeed I would then use it to create a video with more images.
in the code below I find an image inside the pictures library and create a MediaStreamSample from it. this works fine!
then I create a MediaStreamSource with duration of 1 (Sec) and relate it to the sample I Created before. this works fine too!
What doesn't work is the MediaTranscoder instance.
await transcoder.PrepareMediaStreamSourceTranscodeAsync(src, ras, profile);
when I call the above method I get a "Reference not set to an instance" exception. (null Reference exception)
I don't know why this happens... please help me.
StorageFolder cameraFolder = KnownFolders.CameraRoll;
IReadOnlyList<StorageFile> fileList = await cameraFolder.GetFilesAsync();
var query = fileList.Where(f => f.Name.StartsWith("JeyLapse")).ToList();
var stream = await query[0].OpenStreamForReadAsync();
MediaStreamSample sample =
await MediaStreamSample.CreateFromStreamAsync(stream.AsInputStream(), (uint)stream.Length, new TimeSpan());
MediaStreamSource src = new MediaStreamSource(new VideoStreamDescriptor(VideoEncodingProperties.CreateMpeg2()));
src.Duration = TimeSpan.FromSeconds(1);
src.SampleRequested += (sender, args) =>
{
args.Request.Sample = sample;
};
src.Starting += (sender, args) => args.Request.SetActualStartPosition(new TimeSpan());
src.SwitchStreamsRequested += (sender, args) => args.Request.GetDeferral().Complete();
MediaTranscoder transcoder = new MediaTranscoder();
MediaEncodingProfile profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
var newFile = await KnownFolders.VideosLibrary.CreateFileAsync("tryJeylapse", CreationCollisionOption.GenerateUniqueName);
var writestr = await newFile.OpenStreamForWriteAsync();
var ras = writestr.AsRandomAccessStream();
transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default;
var trans = await transcoder.PrepareMediaStreamSourceTranscodeAsync(src, ras, profile);
await trans.TranscodeAsync();
Related
I Have a bufferarray comes from a rest endpoint I have created with Java that returns a byte[] array ; so I managed to get the array with HTTP (I am using Angular) now I want to play the audio in the browser. I have done some research and I found the web audio API but the error is that I can not decode the array.
context = new AudioContext();
audioArray : ArrayBuffer;
buf ;
let arrayBuffer = new ArrayBuffer(this.audioArray.byteLength);
let bufferView = new Uint8Array(arrayBuffer);
for (let i = 0; i < this.audioArray.byteLength; i++) {
bufferView[i] = this.audioArray[i];
}
console.log(arrayBuffer);
// this function should decode the array but the error occurs
// DOMException: Unable to decode audio data
this.context.decodeAudioData(this.audioArray).then((buffer)=>{
this.buf = buffer;
this.play();
}).catch((error)=>{
console.log(error);
});
console.log(this.audioArray);
play() {
let source = this.context.createBufferSource();
source.buffer = this.buf;
source.connect(this.context.destination);
source.start(0);
}
And I am getting the array in ngOnInit function by calling the rest API:)
this.radioService.generateVoiceMethode().subscribe(res => {
console.log(res);
this.audioArray = new ArrayBuffer(res.byteLength);
this.audioArray = res;
console.log(this.audioArray);
});
Though this is an old question, I am sharing an answer that worked for me. May be useful for some one in the future.
async play(data: ArrayBuffer) {
const context = new AudioContext();
const buffer = await context.decodeAudioData(data);
const source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start();
}
The code above works in Angular 8.
I am trying to blur an image in my new Windows Phone Runtime C# app (WPRT)
I used WriteableBitmapEx NuGet and this code to make my image blured but can't see any changes in my picture . what's going wrong guys ?
public TestXaml()
{
this.InitializeComponent();
....
test();
}
async void test()
{
var ImgFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/TestBG.jpg"));
var wb = new WriteableBitmap(100,100);
using (var strm = await ImgFile.OpenReadAsync())
{
wb = await wb.FromStream(strm);
}
var wb3 = WriteableBitmapExtensions.Convolute(wb, WriteableBitmapExtensions.KernelGaussianBlur5x5);
ImageBrush ib = new ImageBrush();
ib.ImageSource = wb3;
PageBackground.Background = ib;
}
also I tried WriteableBitmapExtensions.KernelGaussianBlur3x3 but still no change
In my windows store app, I allow users to open up a file, it does not exist locally then app will download it and save it the local folder of the app and then try to open it using the code below.
This works intermittently, other time the call returns false.
var launcherOption = new LauncherOptions();
launcherOption.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.Default;
launcherOption.DisplayApplicationPicker = userSettings.ShowApplicationPicker;
bool success;
// fileResponse.File is a StorageFile object
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
Things I have checked for:
The file is not restricted by windows ( eg: I am testing with txt, jpg files, not exe, bin, bat )
My app is visible at the time this call is made
The call is made on the UI Thread by using the code below:
var launcherOption = new LauncherOptions();
launcherOption.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseHalf;
launcherOption.DisplayApplicationPicker = userSettings.ShowApplicationPicker;
var dispatcherObject = CoreApplication.MainView.CoreWindow.Dispatcher;
if (dispatcherObject != null && dispatcherObject.HasThreadAccess == false)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
{
launcherOption.TreatAsUntrusted = true;
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
}
});
}
else
{
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
{
launcherOption.TreatAsUntrusted = true;
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
}
}
if (!success)
{
content.IsContentUpdating = false;
content.ContentStatus = string.Empty;
logger.LogMessage(string.Format("Unable to open file. {0}",
content.Name), LoggingLevel.Error);
}
}
Made sure that the file is not blocked by windows by checking it's properties.
Any other ideas what I might be missing here?
I write the following code to save some images from internet:
public static async Task SaveImage(string name, string uri)
{
var localfolder = ApplicationData.Current.LocalFolder;
var client = new HttpClient();
var imageStream = await client.GetStreamAsync(uri); //Secuencia de bytes
var storageFile = await localfolder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await imageStream.CopyToAsync(outputStream);
}
}
My problem is when I try to set these images store in the Local Storage to a CycleTile because this class needs the Uri's, and I don't know how to provide the uri here. This is what I have:
CycleTileData cycleicon = new CycleTileData();
cycleicon.Title = "Fotopantalla";
cycleicon.Count = 0;
cycleicon.SmallBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileSmall.png", UriKind.RelativeOrAbsolute);
List<Uri> images = new List<Uri>();
for (int i = 0; i < 9; i++)
{
/// tries...
string path1 = "ms-appdata:///local/image" + i + ".jpg";
string path2 = "isostore:/Shared/ShellContent/image" + i + ".jpg";
string path3 = "ms-appdata:///Local/Shared/ShellContent/image" + i + ".jpg";
///
Uri uri = new Uri(path2, UriKind.RelativeOrAbsolute);
images.Add(uri);
}
cycleicon.CycleImages = images;
What am I wrong or what am I missing?
For any ShellTileData related data structures you have to use path2:
"isostore:/Shared/ShellContent/*" if the images are not in the (read only) InstalledLocation folder.
For more details see: http://blogs.msdn.com/b/andy_wigley/archive/2013/04/10/live-apps-creating-custom-tile-and-lock-screen-images.aspx
I have something similar in my code:
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.DirectoryExists("Shared/ShellContent"))
{
store.CreateDirectory("Shared/ShellContent");
}
StorageFolder shellContent = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("Shared", CreationCollisionOption.OpenIfExists);
shellContent = await shellContent.CreateFolderAsync("ShellContent", CreationCollisionOption.OpenIfExists);
Stream imgin = picture.GetImage();
//Picture read stream from Media Library or other input stream
StorageFile new_img = await shellContent.CreateFileAsync(newPictureName);
Stream imgout = await new_img.OpenStreamForWriteAsync();
imgin.CopyTo(imgout);
imgout.Close(); // <- necessary in your code or not?
imgin.Close(); // <-
I'm not sure, whether you really need the Isostore thing at the beginning, but it works, if I haven't done some stupid mistake while shortening the code. ;-)
Also have a look at "StandardTileData.BackgroundImage Property", "Data for Windows Phone" and "How to use the Isolated Storage Explorer tool for Windows Phone" from Microsoft's Dev Center. (The last one is about how to have a look at the saved image file on your device.)
I need to generate the Qr Code for my Windows 8 Store App.Is there any Open Source Qr Code Library which is based on Win Rt.
I have made use of zxing library which is available on codeplex.
The method I wrote is as follows:
I'm making use of the DecodeQRcode with storage file from the camera's CaptureFileAsync method which returns the storage file of the qrImgage.
public async void DecodeQRCode(StorageFile file)
{
// load a jpeg, be sure to have the Pictures Library capability in your manifest
var data = await FileIO.ReadBufferAsync(file);
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
var lsource = new BitmapLuminanceSource(wb);
var binarizer = new HybridBinarizer(lsource);
var bbmp = new BinaryBitmap(binarizer);
var c = new QRCodeReader();
Result res= c.decode(bbmp);
}
While taking the image of the QR code you must make sure that you crop the image properly or else you won't get the expected result.
I have not used this, but ZXing.Net is....
A library which supports decoding and generating of barcodes (like QR
Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images.
and has assembles available for WindowsRT (as well as phone)
You can use the ZXing.NET: https://zxingnet.codeplex.com/
Code for load image to get QR Code result:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".bmp");
StorageFile file = await openPicker.PickSingleFileAsync();
if (null != file)
{
try
{
BitmapImage bitmap = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
bitmap.SetSource(fileStream1);
}
using (IRandomAccessStream fileStream2 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
writeableBitmap.SetSource(fileStream2); IBarcodeReader reader = new BarcodeReader();
var result = reader.Decode(writeableBitmap);
txt1.Text = result.ToString();
}
}
catch (Exception exception)
{
//
}
}
Code for get QR from camera (use the MSDN demo: http://code.msdn.microsoft.com/windowsapps/CameraCaptureUI-Sample-845a53ac and customized):
private async void CapturePhoto_Click(object sender, RoutedEventArgs e)
{
try
{
rootPage.NotifyUser("", NotifyType.StatusMessage);
// Using Windows.Media.Capture.CameraCaptureUI API to capture a photo
CameraCaptureUI dialog = new CameraCaptureUI();
Size aspectRatio = new Size(1, 1);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream1);
}
CapturedPhoto.Source = bitmapImage;
ResetButton.Visibility = Visibility.Visible;
ZXing.BarcodeReader br = new ZXing.BarcodeReader();
WriteableBitmap wrb = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
BitmapImage img = new BitmapImage();
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
using (IRandomAccessStream fileStream2 = await file.OpenAsync(FileAccessMode.Read))
{
wrb.SetSource(fileStream2);
}
var res = br.Decode(wrb);
rootPage.NotifyUser(res.ToString(), NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser("No photo captured.", NotifyType.StatusMessage);
}
}
catch (Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}
}