Roman
Roman

Reputation: 2079

How to save MP3 file from the internet on Windows Phone 7?

I'm trying to download and save an .mp3 file from the internet, but got stuck with stream from the external link:

private void saveSound()
    {
        IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
        using (var fs = new IsolatedStorageFileStream("123.mp3", FileMode.Create, iso))
        {
            //Here should be this Stream from the Internet...
            //Uri: "http://my-site.com/mega-popular-song.mp3"
            StreamResourceInfo rs = new StreamResourceInfo(stream, "audio/mpeg");
            int count = 0;
            byte[] buffer = new byte[4096];
            while (0 < (count = rs.Stream.Read(buffer, 0, buffer.Length)))
            {
                fs.Write(buffer, 0, count);
            }
            fs.Close();

        }
    }

What should this stream look like? What is the best way to download and save .mp3 files?

Upvotes: 1

Views: 2167

Answers (1)

Abbas
Abbas

Reputation: 14432

I'm sure this article gets you there. Like Bob mentioned, you'll have to use a WebClient. Basically this is the code that does the magic:

wc.OpenReadCompleted += ((s, args) =>
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (store.FileExists(fileName))
            store.DeleteFile(fileName);

        using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
        {
            byte[] bytesInStream = new byte[args.Result.Length];
            args.Result.Read(bytesInStream, 0, (int)bytesInStream.Length);
            fs.Write(bytesInStream, 0, bytesInStream.Length);
            fs.Flush();
        }
    }
});

But I would read the complete article to fully understand what happens. Hope this helps!

Upvotes: 1

Related Questions