Isolated Storage to Save and Read MP3 Files From Windows Phone 7


Introduction

In this article we are going to explore the phenomenon of playing a MP3 file programmatically. Further in this we will see how to save and read MP3 files from Windows Phone 7 using isolated storage space. Since we are all very familiar with isolated storage, which is a type of virtual storage, by using it we can create a virtual space in the local memory of mobiles. Later by using that we can save and read any type of file from that type of storage; it stores all the files locally and from this local storage we can gain access to these files easily. So this is all about how to save an MP3 file from Windows Phone 7 and later we can read that file from isolated storage easily. To accomplish such type of task we have to care on the two major class named as BinaryWriter and BinaryReader which is used to read the MP3 file. As we know that every MP3 file also is in binary format so first of all to save it first of all we have to save that file on saving first of all we will use the BinaryWriter to write that binary code to the isolated storage and inside it we will take a BinaryReader class which will read the MP3 file and will save to the isolated storage and later we can read that binary file from isolated storage. So let's see the steps to accomplish such type of task which is given below.

Step 1: In this step first of all we have to open a Windows Phone application; let us see how you will open it.

  • Go to Visual Studio 2010
  • File->New->Project
  • Select the template named as Silverlight for Windows Phone
  • Select the Windows Phone application
  • Give it whatever name you want to.   

Step_1_1fig.jpg

Step_1_2fig.jpg

Step 2: In this step we will see that there are some important resources or namespaces which you have to add to the MainPage.xaml.cs file; let us see the namespaces which is given below.

Step_2_fig.jpg

Step 3: In this step you have to add a MP3 file inside your project from the media library of your computer. Let's see the figure given below that how could you do this.

Go to Solution Explorer

Select the project and right-click on it.

Step_3_1fig.jpg

Select add existing item.

Step_3_2fig.jpg

Choose the folder from where you have to add that MP3 file.

Step_3_3fig.jpg

Click OK. You will see the figure given below after you added that file which will be like:

Step_3_4fig.jpg

Step 4: In this step we will initialize a const string which will store the MP3 file name in a string and the initialization of that string is given below.

Step_4fig.jpg

Step 5: In this step you have to see that first of all we will write the code for the save button; let us see how we will save such a type of file which is given below.

Code:

private void button1_Click(object sender, RoutedEventArgs e)
  {
      StreamResourceInfo SRI = Application.GetResourceStream(new Uri(My_F_Name, UriKind.Relative));
      using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
      {
          if (ISF.FileExists(My_F_Name))
          {
              ISF.DeleteFile(My_F_Name);
          }
          using (IsolatedStorageFileStream FS = new IsolatedStorageFileStream(My_F_Name, FileMode.Create, ISF))
          {
              using (BinaryWriter BW = new BinaryWriter(FS))
              {
                  Stream S = SRI.Stream;
                  long lg = S.Length;
                  byte[] bff = new byte[32];|
                  int Count = 0;
                  using (BinaryReader BR = new BinaryReader(SRI.Stream))
                  {
                      // read file in chunks in order to reduce memory consumption and increase performance
                      while (Count < lg)
                      {
                          int actual = BR.Read(bff, 0, bff.Length);
                          Count += actual;
                          BW.Write(bff, 0, actual);
                      }
                      MessageBox.Show("Mp3 file has been saved");
                  }
              }
          }
      }
  }

Step 6: In this step we will see the code for button read which will read the file from the isolated storage which is given below.

Code:

private void button2_Click(object sender, RoutedEventArgs e)
  {
      using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
      {
          using (IsolatedStorageFileStream FS = ISF.OpenFile(My_F_Name, FileMode.Open, FileAccess.Read))
          {
              this.mediaElement.SetSource(FS);
              MessageBox.Show("You should plugin via headphone to read the mp3 file ");
          }
      }
  }

Step 7: In this step we will see the complete code for the MainPage.xaml.cs file which is given below.

Code:

using
System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Resources;
namespace mymp3fileproject
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        private const string My_F_Name = "bodyguard04(http://www.songs.pk/).mp3";
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            StreamResourceInfo SRI = Application.GetResourceStream(new Uri(My_F_Name, UriKind.Relative));
            using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (ISF.FileExists(My_F_Name))
                {
                    ISF.DeleteFile(My_F_Name);
                }
                using (IsolatedStorageFileStream FS = new IsolatedStorageFileStream(My_F_Name, FileMode.Create, ISF))
                {
                    using (BinaryWriter BW = new BinaryWriter(FS))
                    {
                        Stream S = SRI.Stream;
                        long lg = S.Length;
                        byte[] bff = new byte[32];
                        int Count = 0;
                        using (BinaryReader BR = new BinaryReader(SRI.Stream))
                        {
                            // Now we have to read file in chunks in order to reduce memory consumption and increase performance
                            while (Count < lg)
                            {
                                int actual = BR.Read(bff, 0, bff.Length);
                                Count += actual;
                                BW.Write(bff, 0, actual);
 
                            }
                            MessageBox.Show("Mp3 file has been saved");
                        }
                    }
                }
            }
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream FS = ISF.OpenFile(My_F_Name, FileMode.Open, FileAccess.Read))
                {
                    this.mediaElement.SetSource(FS);
                    MessageBox.Show("You should plugin via headphone to read the mp3 file ");
                }
            }
        }
    }
}

Step 8: In this step we will see the code for the MainPage.xaml file which is given below.

Code:

<phone:PhoneApplicationPage
    x:Class="mymp3fileproject.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible
="True">
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="PageTitle" Text="My MP3 file" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"
              FontFamily
="Comic Sans MS"><TextBlock.Foreground><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <
GradientStop Color="Black" Offset="0" />
                <
GradientStop Color="#FF5DFFBE" Offset="1" />
                </
LinearGradientBrush>
            </
TextBlock.Foreground></TextBlock>
        </StackPanel>
        <!--ContentPanel - place additional content here-->
        <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel.Background>
                <RadialGradientBrush>
                    <GradientStop Color="Black" Offset="0" />
                    <GradientStop Color="#FFFFBF82" Offset="1" />
                </RadialGradientBrush>
            </StackPanel.Background>
            <Button Content="Save Mp3 File" x:Name="button1" Click="button1_Click" FontFamily="Comic Sans MS" FontSize="32">
                <Button.Background>
                    <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="#FFC8FF79" Offset="1" />
                    </LinearGradientBrush>
                </Button.Background>
                <Button.Foreground>
                    <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="#FFFF24FF" Offset="1" />
                    </LinearGradientBrush>
                </Button.Foreground>
            </Button>
            <Button Content="Read Mp3 File" x:Name="button2" Click="button2_Click" FontSize="32" FontFamily="Comic Sans MS" Foreground="#FF1F0A19">|
                <Button.Background>
                    <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="#FF7EFFE5" Offset="1" />
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
            <MediaElement x:Name="mediaElement" AutoPlay="True"/>
        </StackPanel>
    </Grid>
</
phone:PhoneApplicationPage>

Step 9: In this step we will see the design page of the MainPage.xaml file; let us see the figure given below.

Designing_image.jpg

Step 10: In this step we have to run the application by pressing F5 and the related output is given below.

Output 1: It's the default output whenever we run the Windows Phone application.

Output1.jpg

Output 2: In this output we will see that whenever we click on the save button it will show a message that your file has been saved.

output2.jpg

Output 3: Further in this output we will see that whenever you click on the button read then a message box will open and give some advise that you have to plug-in with headphone to read or listen that MP3 file after click OK you just see that the our program is working correctly you can listen that audio file easily.

Output3.jpg

Here are some other resources which may help you


Using Isolated Storage to Save And Get an Image in Windows Phone 7Save And Read Data From Isolated Storage in Windows Phone 7Multitasking or Tombstoning and Isolated Storage in Windows Phone 7

Isolated Storage Explorer Tool in Window Phone 7Windows Azure Storage Client Library For Windows Phone: Part 1

Up Next
    Ebook Download
    View all
    Learn
    View all