Windows Phone 8.1 Load Sound Issue with StreamResourceInfo - c#

I am converting an app from WP7 to WP8.1 The codes for WP7 no longer works for WP8.1
sfxLeft = new MediaElement();
sfxRight = new MediaElement();
StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri(wav, UriKind.Relative));
var sfx = SoundEffect.FromStream(streamInfo.Stream);
sfxLeft = sfx.CreateInstance();
sfxRight = sfx.CreateInstance();
StreamResourceInfo does not exists for WP8.1 anymore. Anyone know how I can re-write this line to make it work for WP8.1?
Updated Code.
Here's the new code below, but now it seems the sfxLeft and sfxRight are always NULL. I thought the below code would set sfxLeft and sfxRight, but it's still NULL.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
test();
}
async private Task test()
{
Uri wav = new Uri("ms-appx:///Assets/eye_poke.wav", UriKind.RelativeOrAbsolute);
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(wav);
stream = await file.OpenStreamForReadAsync();
sfxLeft = SoundEffect.FromStream(stream).CreateInstance();
sfxRight = SoundEffect.FromStream(stream).CreateInstance();
}

To play sound using XNA Framework in Windows Phone 8.1 Silverlight App
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(wav);
Stream stream = await file.OpenStreamForReadAsync();
SoundEffect Sound1 = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
Sound1.Play();
Or you can use MediaElement for both RT and Silverlight but they are in different namespace,
MediaElement mediaElement1 = new MediaElement();
mediaElement1.Source = wav
mediaElement1.AutoPlay = false;
rootGrid.Children.Add(mediaElement1)

Thanks. I figured it out by using the media element in XAML and then add codes in c# to play it.

Related

Download Image UWP (C#)

I writing application for Windows 10 mobile.
I have Image in my XAML.
<Image x:Name="productimage" HorizontalAlignment="Left" Height="146" VerticalAlignment="Top" Width="135"/>
I need to download image from URL and put it to Image
How I can do this?
Thank's with help.
You can try this snipet
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
...
System.Net.Http.HttpResponseMessage imageResponse = await client.GetAsync(imageUrl);
// A memory stream where write the image data
Windows.Storage.Streams.InMemoryRandomAccessStream randomAccess =
new Windows.Storage.Streams.InMemoryRandomAccessStream();
Windows.Storage.Streams.DataWriter writer =
new Windows.Storage.Streams.DataWriter(randomAccess.GetOutputStreamAt(0));
// Write and save the data into the stream
writer.WriteBytes(await imageResponse.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
// Create a Bitmap and assign it to the target Image control
Windows.UI.Xaml.Media.Imaging.BitmapImage bm =
new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bm.SetSourceAsync(randomAccess);
productimage.Source = bm;
It's not my snipet, but should work also with UWP. UWP is very similar to Windows 8.1. So you can try to search for WinRT examples
I found answer on my question
It's simple
string url = "url";
productimage.Source = new BitmapImage(new Uri(url, UriKind.Absolute));
Thank's to # Eldar Dordzhiev
This code is in VB.Net. I guess you could read it and convert to C#. I just wanted to help. Use Windows.Web.Http for UWP as System.Net.Htpp is being depreciated.
Imports Windows.Web.Http
...
Dim client as New HttpClient
Dim response = Await client.GetBufferAsync(ImgUri)
stream = response.AsStream
Dim mem = New MemoryStream()
Await stream.CopyToAsync(mem)
mem.Position = 0
Dim img As New BitmapImage
img.SetSource(mem.AsRandomAccessStream)
Return img

How to get ImageStream from MediaCapture?

In WP 8 I used PhotoCamera to make a camera app and to save the image in camera roll I used this method:
private void cam_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
{
string fileName = "photo.jpg";
MediaLibrary library = new MediaLibrary();
library.SavePictureToCameraRoll(fileName, e.ImageStream);
}
In WPSL 8.1 I use MediaCapture and I use the same style to save image in camera roll but I don't know how to retrieve ImageStream from MediaCapture like in e.ImageStream. I am open to suggestions even with other programming style for saving to camera roll.
var file = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(IMAGECAPTURE_FILENAME, Windows.Storage.CreationCollisionOption.ReplaceExisting);
await _exceptionHandler.Run(async () =>
{
await _mediaCapture.CapturePhotoToStorageFileAsync(_imageEncodingProperties, file);
var photoStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
await bitmap.SetSourceAsync(photoStream);
});
The above is taken from a UWP app to save an image to storage, then read it from disk as a stream. I've never been able to capture the image directly as a stream.

Unzipping files in WP8.1 Using SharpZipper

I am trying to use SharpZip.unzipper for my windows phone 8.1. However it is not reading some of the code. Since i am fairly new to windows phone development please let me know the alternatives of following code for WP8.1
using System.Windows.Resources;
public Stream GetFileStream(string filename)
{
if (fileEntries == null)
fileEntries = ParseCentralDirectory(); //We need to do this in case the zip is in a format Silverligth doesn't like
long position = this.stream.Position;
this.stream.Seek(0, SeekOrigin.Begin);
Uri fileUri = new Uri(filename, UriKind.Relative);
StreamResourceInfo info = new StreamResourceInfo(this.stream, null);
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);
this.stream.Position = position;
if (stream != null)
return stream.Stream;
return null;
}
Windows.Resources seems missing
I can't call StreamResourceInfo, System.Windows.Application
I have tried using App. but there is no function for GetResourceSteam
I am not sure what to do here
There are quite a few differences between WP8.1 runtime and WP8.1 Silverlight.
The code sample that you have will run on WP8.0 SL and WP8.1 SL.
It looks like you created a Windows Phone 8.1 runtime project. There is no System.Windows.Application.GetResourceStream()
Either convert it to a compatible 8.1 runtime stream or recreate your project to target Silverlight instead.
// sample
private async void ZipLibraryTest()
{
// create the full path
string zip = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "filename.zip");
// create the storage file with the file name
StorageFile sf = await StorageFile.GetFileFromPathAsync(zip);
// create the IO Stream
using (System.IO.Stream output = await sf.OpenStreamForWriteAsync())
{
// open the zip file for writing, use the stream from the file
ZipFile zf = ZipFile.Create(output);
// rest of your code
// ...
// ...
// close the zip file
zf.Close();
}
}

Sound Effect Class in background agent

I want to be able to play an audio file (a sound basically) from the background agent. I am using the following two approaches :
1)
SoundEffectInstance ClockTickInstance;
StreamResourceInfo ClockTickStream;
SoundEffect ClockTickSound;
try {
ClockTickStream = Application.GetResourceStream(new Uri(
#"AudioFiles/NewHighScore.wav", UriKind.Relative));
ClockTickSound = SoundEffect.FromStream(ClockTickStream.Stream);
ClockTickInstance = ClockTickSound.CreateInstance();
ClockTickInstance.IsLooped = true;
ClockTickInstance.Volume = 1.0f;
ClockTickInstance.Pitch = 1.0f;
ClockTickInstance.Play();
ClockTickInstance.Stop();
}
OR
2)
var localFolder = Package.Current.InstalledLocation;
Stream fileStream = await localFolder.OpenStreamForReadAsync("NewHighScore.wav");
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, System.Convert.ToInt32(fileStream.Length));
fileStream.Close();
SoundEffect soundefct = new SoundEffect(buffer, 16000, AudioChannels.Mono);
FrameworkDispatcher.Update();
soundefct.Play();
When i run the code from the xaml.cs file (i.e. from the foreground app) evrything works fine and the sound is played.
But from the background agent, the code runs but no sound is heard.
What could be the problem?
the following article shows the list of APIs that can be used while the app is running in the background -
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662941(v=vs.105).aspx

Download and Save image in Pictures Library through Windows 8 Metro XAML App

I am trying to develop a simple Windows 8 Metro app which simply downloads an image file from a given URL (say http://sample.com/foo.jpg) and then save it to Pictures Library.
I have an image control in the UI to display the downloaded image.
I'm also facing difficulty in setting the image source for the image control to the newly downloaded image (actually I'm not even able to download it).
Also, is it possible to store the image file in a particular folder in the Pictures library (if it doesn't exist, then the app should create it)?
I'm really stuck here.
Please help me.
Here's some rough code that I believe accomplishes what you want. It assumes you have two image controls (Image1 and Image2) and that you have the Pictures Library capability checked in the manifest. Take a look at the XAML images sample as well
Uri uri = new Uri("http://www.picsimages.net/photo/lebron-james/lebron-james_1312647633.jpg");
var fileName = Guid.NewGuid().ToString() + ".jpg";
// download pic
var bitmapImage = new BitmapImage();
var httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(uri);
byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();
// create a new in memory stream and datawriter
using (var stream = new InMemoryRandomAccessStream())
{
using (DataWriter dw = new DataWriter(stream))
{
// write the raw bytes and store
dw.WriteBytes(b);
await dw.StoreAsync();
// set the image source
stream.Seek(0);
bitmapImage.SetSource(stream);
// set image in first control
Image1.Source = bitmapImage;
// write to pictures library
var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
fileName,
CreationCollisionOption.ReplaceExisting);
using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
}
}
}
// read from pictures library
var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
using ( var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read) )
{
bitmapImage.SetSource(pictureStream);
}
Image2.Source = bitmapImage;
}

Categories

Resources