I am trying to download an audio and saving to isolated storage and saving to emulator.
I tried with the following code.
WebClient m_webClient = new WebClient();
m_webClient.OpenReadAsync(fileUri);
m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_ImageOpenReadCompleted);
m_webClient.AllowReadStreamBuffering = true;
private static void webClient_ImageOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var isolatedfile = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, System.IO.FileMode.Create, isolatedfile))
{
byte[] buffer = new byte[e.Result.Length];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
}
SaveFileMP3(_fileName);
}
private static void SaveFileMP3(string _fileName)
{
MediaLibrary lib = new MediaLibrary();
Uri songUri = new Uri(_fileName, UriKind.RelativeOrAbsolute);
MediaLibraryExtensions.SaveSong(lib, songUri, null, SaveSongOperation.CopyToLibrary);
}
The problem I am facing is, the audio getting saved to the emulator but not with the extension. Suppose the file name "test.MP3", it is saved as "test" and the duration is always 0:0:00 irrespective to the original duration.
I have added Audio capability too in the manifest file.
Following is the screenshot while saving the song, which has many exceptions in it.
Please correct if something is wrong with code. Thanks in advance.
By adding the line of lib.savesong worked perfectly instead of using mediaLibraryExtensions.
private static void SaveFileMP3(string _fileName)
{
MediaLibrary lib = new MediaLibrary();
Uri songUri = new Uri(_fileName, UriKind.RelativeOrAbsolute);
lib.SaveSong(songUri, null, SaveSongOperation.CopyToLibrary);
//MediaLibraryExtensions.SaveSong(lib, songUri, null, SaveSongOperation.CopyToLibrary);
}
Related
I am able to store media files into the Isolated Storage and able to retrieve the same. Now what I want is to play that file in music player in phone, but music player says "no music found". How can i show my downloaded mp3 files in isolated storage to the media library? I am using this code to download the mp3 file. Is there any way to download the file to the readable storage like (phone memory/ internal storage / memory card)???
void imgDown_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
ToastPrompt toast = new ToastPrompt();
toast.Foreground = new SolidColorBrush(Colors.Black);
toast.FontSize = 20;
toast.Background = new SolidColorBrush(Colors.Yellow);
toast.Message = "Please wait";
toast.Show();
try
{
//Create a webclient that'll handle your download
WebClient client = new WebClient();
//Run function when resource-read (OpenRead) operation is completed
client.OpenReadCompleted += client_OpenReadCompleted;
//Start download / open stream
client.OpenReadAsync(new Uri(streamUrl));
}
catch (Exception ex)
{
toast.Message = "Downloading error";
toast.Show();
}
}
async void client_OpenReadCompleted(object sender,
OpenReadCompletedEventArgs e)
{
ToastPrompt toast = new ToastPrompt();
toast.Foreground = new SolidColorBrush(Colors.Black);
toast.FontSize = 20;
toast.Background = new SolidColorBrush(Colors.Yellow);
toast.Message = "Downloading starts";
toast.Show();
try
{
byte[] buffer = new byte[e.Result.Length];
//Store bytes in buffer, so it can be saved later on
await e.Result.ReadAsync(buffer, 0, buffer.Length);
using (IsolatedStorageFile file
IsolatedStorageFile.GetUserStoreForApplication())
{
//Create file
using (IsolatedStorageFileStream stream =
file.OpenFile(titleUrl+".mp3", FileMode.Create))
{
//Write content stream to file
await stream.WriteAsync(buffer, 0, buffer.Length);
}
// StorageFolder local =
Windows.Storage.ApplicationData.Current.LocalFolder;
//StorageFile storedFile = await local.GetFileAsync(titleUrl +
".mp3");
toast.Message = "Downloading complete";
toast.Show();
}
catch (Exception ex)
{
toast.Message = "We could not finish your download. Error ";
toast.Show();
}
It looks like you need to use the MediaLibraryExtensions.SaveSong method (see https://msdn.microsoft.com/library/microsoft.xna.framework.media.PhoneExtensions.medialibraryextensions.savesong(v=xnagamestudio.42).aspx)
You'll need to add the ID_CAP_MEDIALIB_AUDIO capability to your app, and get a URI for the file on the Isolated Storage to pass to that method.
There's some more information on Data for Windows Phone on MSDN.
I am maintaining Windows Phone 7 application. Everything worked fine. Everything still works fine on WP 8. But on WP7 app breaks. I have .sdf database in project. Below is the code I use to stream it in isolated storage.
using (Stream input = Application.GetResourceStream(new Uri("Assets\\myDB.sdf", UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile("myDB.sdf"))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
var listOfCities = ModelUtil.GetCities().OrderBy(c => c.Name);
This is GetCities method
public static List<ListPickerData> GetCities()
{
List<ListPickerData> cities = new List<ListPickerData>();
using (myDataContext context = new myDataContext(ModelUtil.ConnectionString))
{
var data = context.Cities.ToList();
...
}
return cities;
}
And this is where it breaks:
Does anyone know what happened? Thanks!
Try to extract the database file from the working WP8 install, and re-add to your project. Also, what does your connection string look like?
I have an ASP File upload, PostedFile.InputStream, it is giving us the System.IO.Stream. Is this file stream similar to that of getting
System.IO.File.OpenRead("filename");
I have a Rackspace file content saver that gets the input as Stream, it's not getting the correct image displayed when used PostedFile.InputStream.
Normally PostedFile.InputStream and System.IO.Stream are same.
So there is no need of any additional coding for Rackspace.
You can use file.InputStream as the Stream parameter to create the Object of Rackspace cloud files.
Another method which is not required but can test is
byte[] buffer = new byte[file.InputStream.Length];
file.InputStream.Seek(0, SeekOrigin.Begin);
file.InputStream.Read(buffer, 0, Convert.ToInt32(file.InputStream.Length));
Stream stream2 = new MemoryStream(buffer);
You can use this stream also as input for creating object.
This one worked with rackspace cloud , It can upload file from client side to rackspace cloud file. I also used file uploader.
protected void Button1_Click(object sender, EventArgs e)
{
var cloudIdentity = new CloudIdentity() { Username = "Rackspace_user_name", APIKey = "Rackspace_api" };
var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
byte[] buffer = new byte[FileUpload1.FileBytes.Length];
FileUpload1.FileContent.Seek(0, SeekOrigin.Begin);
FileUpload1.FileContent.Read(buffer, 0, Convert.ToInt32(FileUpload1.FileContent.Length));
Stream stream2 = new MemoryStream(buffer);
try
{
using (FileUpload1.PostedFile.InputStream)
{
cloudFilesProvider.CreateObject("Containers_name", stream2, FileUpload1.FileName); //blockBlob.UploadFromStream(fileASP.PostedFile.InputStream);
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
I am making a WP7 app which download all my twitter feed. In this I want to download all the profile images and store them locally and use them, so that they would be downloaded every time i open the app. Please suggest any of the methods to do so.
What I am doing: using a WebClient to download the image
public MainPage()
{
InitializeComponent();
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg"));
}
and store it to a file.
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName1))
myIsolatedStorage.DeleteFile(fileName1);
var fileName1 = "Image.jpg";
using (var fileStream = new IsolatedStorageFileStream(fileName1, FileMode.Create, myIsolatedStorage))
{
using (var writer = new StreamWriter(fileStream))
{
var length = e.Result.Length;
writer.WriteLine(e.Result);
}
var fileStreamLength = fileStream.Length;
fileStream.Close();
}
}
Now I am trying to set the image to a BitMapImage
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName1, FileMode.Open, FileAccess.Read))
{
var fileStreamLength2 = fileStream.Length;
bi.SetSource(fileStream);
}
}
But I am not able to set source of the BitmapImage. It is throwing System.Exception and nothing specific. Am I doing it the right way? I mean the procedure.
EDIT Another observation is the fileStreamLength and fileStreamLength2 are different.
You're not supposed to use DownloadString to download a binary file. Use OpenReadAsync instead, and save the binary array to the isolated storage.
DownloadString will try to convert your data to UTF-16 text, which of course can't be right when dealing with a picture.
I am new to the windows phone 7 application development. I am accessing the picture library by using the PhotoChooserTask class. After selecting one of the picture from picture library I want to add that image (.jpg file) from picture library to the images folder of my application. How to do this ? I am using the following code
public partial class MainPage : PhoneApplicationPage
{
PhotoChooserTask photoChooserTask;
// Constructor
public MainPage()
{
InitializeComponent();
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
photoChooserTask.Show();
}
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
}
}
}
I want to add the the selected image dynamically to images folder of my application. how to do this? Can you please provide me any code or link through which I can resolve the above issue ?
Here's an example of saving the selected picture to IsolatedStorage and then reading it out to display it on the page:
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var contents = new byte[1024];
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var local = new IsolatedStorageFileStream("image.jpg", FileMode.Create, store))
{
int bytes;
while ((bytes = e.ChosenPhoto.Read(contents, 0, contents.Length)) > 0)
{
local.Write(contents, 0, bytes);
}
}
// Read the saved image back out
var fileStream = store.OpenFile("image.jpg", FileMode.Open, FileAccess.Read);
var imageAsBitmap = PictureDecoder.DecodeJpeg(fileStream);
// Display the read image in a control on the page called 'MyImage'
MyImage.Source = imageAsBitmap;
}
}
}
You can refer to the RTM release notes on the revised Photo Chooser API or the doco a bit further down the page here.
How to: Create a Photo Extras Application for Windows Phone
In fact, once you obtain the stream, you can convert it to byte and store locally. Here is what you should have in your Task_Completed event handler:
using (MemoryStream stream = new MemoryStream())
{
byte[] contents = new byte[1024];
int bytes;
while ((bytes = e.ChosenPhoto.Read(contents, 0, contents.Length)) > 0)
{
stream.Write(contents, 0, bytes);
}
using (var local = new IsolatedStorageFileStream("myImage.jpg", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
{
local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
}
}