简体   繁体   English

NAudio播放录制文件中的一部分音频

[英]NAudio Play part of audio from recording file

Using NAudio, while recording audio to a file I need to play a part of that file with offsetSampleProvider.SkipOver / offsetSampleProvider.Take 使用NAudio,在将音频录制到文件时,我需要使用offsetSampleProvider.SkipOver / offsetSampleProvider.Take播放该文件的一部分

The problem is that I can't open the file with AudioFileReader because it is already in use by WaveFileWriter. 问题是我无法使用AudioFileReader打开文件,因为WaveFileWriter已在使用它。

I found a solution. 我找到了解决方案。

Here is the source code. 这是源代码。

using System;
using System.Windows.Forms;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using static System.Environment;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        WaveFileWriter fileWriter;
        WaveOut outputSound;
        WaveIn waveSource;
        RawSourceWaveStream RSS;
        OffsetSampleProvider offsetSampleProvider;
        Stream sourceStream;

        string fileName = GetFolderPath(SpecialFolder.CommonApplicationData) + "\\temp.wav";

        public Form1()
        {
            InitializeComponent();

            outputSound = new WaveOut();
            waveSource = new WaveIn();
            waveSource.WaveFormat = new WaveFormat(8000, 16, 1);
            waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
            fileWriter = new WaveFileWriter(fileName, waveSource.WaveFormat);
            sourceStream = new MemoryStream();

            waveSource.StartRecording();
        }

        private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
        {
            fileWriter.Write(e.Buffer, 0, e.BytesRecorded);
            sourceStream.Write(e.Buffer, 0, e.BytesRecorded);
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            RSS = new RawSourceWaveStream(sourceStream, waveSource.WaveFormat);
            RSS.Position = 0;
            offsetSampleProvider = new OffsetSampleProvider(RSS.ToSampleProvider());
            offsetSampleProvider.SkipOver = TimeSpan.FromMilliseconds(0);
            offsetSampleProvider.Take = TimeSpan.FromMilliseconds(3000);
            outputSound.Init(offsetSampleProvider);
            outputSound.Play();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM