windows-phone-8windows-phoneisolatedstoragefile

Recording sound in temporary file on windows phone 8


This is my code for recording sound in temporary file. when i record sound and then listen to playback, everything goes well, but when i click again on playback button, i get this error:

enter image description here

How can i solve this problem?

Code:

using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using Coding4Fun.Toolkit.Audio;
using Coding4Fun.Toolkit.Audio.Helpers;

namespace AudioRecorder.UserControls
{
public partial class SoundRecorderPanel : UserControl
{

    private MicrophoneRecorder _recorder = new MicrophoneRecorder();
    private List<IsolatedStorageFileStream>  _audioList = new List<IsolatedStorageFileStream>();
    private int _counter;
    public SoundRecorderPanel()
    {
        InitializeComponent();
    }

    private void ButtonRecord_OnChecked(object sender, RoutedEventArgs e)
    {
       _recorder.Start();
    }

    private void ButtonRecord_OnUnchecked(object sender, RoutedEventArgs e)
    {
        _recorder.Stop();  
        SaveTempAudio(_recorder.Buffer);
    }

    private void SaveTempAudio(MemoryStream buffer)
    {

        if (_counter==2)
            return;

        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
        {
            var bytes = buffer.GetWavAsByteArray(_recorder.SampleRate);
            var tempFileName = "tempwaveFile_"+_counter;
            IsolatedStorageFileStream audioStream = isoStore.CreateFile(tempFileName);

            audioStream.Write(bytes,0,bytes.Length);
            _audioList.Add(audioStream);

            _counter++;
        }
    }

    private void ButtonPlayBack_OnClick(object sender, RoutedEventArgs e)
    {
        var index = int.Parse(((Button) sender).Tag.ToString());
        var audioPlayer = new MediaElement {AutoPlay = true};

        if (index < _audioList.Count)
        {

                audioPlayer.SetSource(_audioList[index]);
                LayoutRoot.Children.Add(audioPlayer);
                audioPlayer.Play();

        }
    }

}

}


Solution

  • You can 100% use a using block. Issue was how you were attempting to access the stream in the separate event. Reopen it rather than attempt to save a reference in an index to the stream.

    using (var stream = new IsolatedStorageFileStream(_fileName, FileMode.Open, storageFolder))
    {
        playBack.SetSource(stream);
        playBack.Play();
    }
    

    Use the sample code: https://coding4fun.codeplex.com/SourceControl/latest#source/Coding4Fun.Toolkit.Test.WindowsPhone.Common/Samples/Audio.xaml.cs