【问题标题】:Record from microphone and playback in Windows Phone从麦克风录制并在 Windows Phone 中播放
【发布时间】:2012-01-07 16:56:56
【问题描述】:

我正在开发的应用程序的一部分允许用户使用麦克风录制任何内容。为了从麦克风录音,我使用了Microphone Code sample by Microsoft 中给出的代码。我只是对代码进行了一些更改,将 wav 标头写入流,以便我可以将录音作为波形文件存储在独立存储中。

private void recordButton_Click(object sender, EventArgs e)
        {
            // Get audio data in 1/2 second chunks
            microphone.BufferDuration = TimeSpan.FromMilliseconds(500);

            // Allocate memory to hold the audio data
            buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];

            // Set the stream back to zero in case there is already something in it
            stream.SetLength(0);

            //Write wav header
            WriteWavHeader(microphone.SampleRate);

            // Start recording
            microphone.Start();

            SetButtonStates(false, false, true,false);
            UserHelp.Text = "record";
            StatusImage.Source = microphoneImage;
            StatusImage.Visibility = System.Windows.Visibility.Visible;
        }

        public void WriteWavHeader(int sampleRate)
        {
            const int bitsPerSample = 16;
            const int bytesPerSample = bitsPerSample / 8;
            var encoding = System.Text.Encoding.UTF8;
            // ChunkID Contains the letters "RIFF" in ASCII form (0x52494646 big-endian form).
            stream.Write(encoding.GetBytes("RIFF"), 0, 4);

            // NOTE this will be filled in later
            stream.Write(BitConverter.GetBytes(0), 0, 4);

            // Format Contains the letters "WAVE"(0x57415645 big-endian form).
            stream.Write(encoding.GetBytes("WAVE"), 0, 4);

            // Subchunk1ID Contains the letters "fmt " (0x666d7420 big-endian form).
            stream.Write(encoding.GetBytes("fmt "), 0, 4);

            // Subchunk1Size 16 for PCM.  This is the size of therest of the Subchunk which follows this number.
            stream.Write(BitConverter.GetBytes(16), 0, 4);

            // AudioFormat PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.
            stream.Write(BitConverter.GetBytes((short)1), 0, 2);

            // NumChannels Mono = 1, Stereo = 2, etc.
            stream.Write(BitConverter.GetBytes((short)1), 0, 2);

            // SampleRate 8000, 44100, etc.
            stream.Write(BitConverter.GetBytes(sampleRate), 0, 4);

            // ByteRate =  SampleRate * NumChannels * BitsPerSample/8
            stream.Write(BitConverter.GetBytes(sampleRate * bytesPerSample), 0, 4);

            // BlockAlign NumChannels * BitsPerSample/8 The number of bytes for one sample including all channels.
            stream.Write(BitConverter.GetBytes((short)(bytesPerSample)), 0, 2);

            // BitsPerSample    8 bits = 8, 16 bits = 16, etc.
            stream.Write(BitConverter.GetBytes((short)(bitsPerSample)), 0, 2);

            // Subchunk2ID Contains the letters "data" (0x64617461 big-endian form).
            stream.Write(encoding.GetBytes("data"), 0, 4);

            // NOTE to be filled in later
            stream.Write(BitConverter.GetBytes(0), 0, 4);
        }

        public void UpdateWavHeader()
        {
            //if (!stream.CanSeek) throw new Exception("Can't seek stream to update wav header");

            var oldPos = stream.Position;

            // ChunkSize  36 + SubChunk2Size
            stream.Seek(4, SeekOrigin.Begin);
            stream.Write(BitConverter.GetBytes((int)stream.Length - 8), 0, 4);

            // Subchunk2Size == NumSamples * NumChannels * BitsPerSample/8 This is the number of bytes in the data.
            stream.Seek(40, SeekOrigin.Begin);
            stream.Write(BitConverter.GetBytes((int)stream.Length - 44), 0, 4);

            stream.Seek(oldPos, SeekOrigin.Begin);
        }

        private void stopButton_Click(object sender, EventArgs e)
        {
            if (microphone.State == MicrophoneState.Started)
            {
                // In RECORD mode, user clicked the 
                // stop button to end recording
                microphone.Stop();
                UpdateWavHeader();
            }
            else if (soundInstance.State == SoundState.Playing)
            {
                // In PLAY mode, user clicked the 
                // stop button to end playing back
                soundInstance.Stop();
            }

            SetButtonStates(true, true, false,true);
            UserHelp.Text = "ready";
            StatusImage.Source = blankImage;
        }

在此之后,如果用户选择保存录音,我会将其保存在隔离存储中。

应用程序中有各种页面,使用麦克风的页面就是其中之一。到此页面的导航是从另一个页面完成的:

NavigationService.Navigate(new Uri("/Mic.xaml", UriKind.Relative));

现在,当在 Mic.xaml 页面上时,如果用户单击硬件后退按钮,无论是否录制任何内容,他都会返回到旧页面。如果他再次从该页面导航到 Mic.xaml 页面然后尝试录制某些内容,则录制的文件似乎没有正确录制。录音好像有问题。

因此,当我们第一次导航到该页面时,录制成功,但当我们第二次或第四次导航时却没有。

我正在模拟器上进行测试

【问题讨论】:

    标签: windows-phone-7.1 windows-phone-7


    【解决方案1】:

    Microsoft 的示例不适用于多页场景,因为它们在离开页面时不会清理资源。

    首先,将 DispatcherTimer 放入一个字段中:

        private DispatcherTimer dt;
    

    然后,更改构造函数以使用该字段而不是初始化新的 dt:

        this.dt = new DispatcherTimer();
    

    最后重写 OnNavigateFrom 方法,检测用户何时离开页面,并清理资源:

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
    
            dt.Stop();
    
            microphone.BufferReady -= this.microphone_BufferReady;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 2018-06-18
      相关资源
      最近更新 更多