6

我有通过 NAudio 提取的音频样本,我知道参数:

  • 渠道
  • 每个样本的字节数,
  • 采样率

如何使用 .Net api / 或其他 .Net 库播放样本

这里代码:

    openFileDialog1.ShowDialog();
    using (var reader = new Mp3FileReader(openFileDialog1.FileName))
    {
        var pcmLength = (int)reader.Length;
        var _leftBuffer = new byte[pcmLength / 2];
        var buffer = new byte[pcmLength];
        var bytesRead = reader.Read(buffer, 0, pcmLength);
        int index = 0;
        for (int i = 0; i < bytesRead; i += 4)
        {
           //extracting only left channel 
           _leftBuffer[index] = buffer[i];
           index++;
           _leftBuffer[index] = buffer[i + 1];
           index++;
         }

         // How to play  _leftBuffer (Single channel, 2 bytes per sample, 44100 samples per secound)
}
4

2 回答 2

2

首先,您需要实现IWaveProviderIWaveProvider使用 NAudio 附带的实现之一WaveProvider16,例如。接下来,使用 using初始化一个WaveOut对象,最后调用。IWaveProviderWaveOut.Init(IWaveProvider Provider)WaveOut.Play()

于 2012-12-19T19:00:21.157 回答
1

是的,我找到了解决方案:A low-level audio player in C#

完整的工作代码:

public partial class Form1 : Form
    {
        private byte[] _leftBuffer;
        private BiQuadFilter _leftFilter;
        private BiQuadFilter _rightFilter;
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            using (var reader = new Mp3FileReader(openFileDialog1.FileName))
            {
                var pcmLength = (int)reader.Length;
                _leftBuffer = new byte[pcmLength / 2];
                var buffer = new byte[pcmLength];
                var bytesRead = reader.Read(buffer, 0, pcmLength);

                int index = 0;
                for (int i = 0; i < bytesRead; i += 4)
                {
                    _leftBuffer[index] = buffer[i];
                    index++;
                    _leftBuffer[index] = buffer[i + 1];
                    index++;
                }
                var player = new WaveLib.WaveOutPlayer(-1, new WaveLib.WaveFormat(44100, 16, 1), _leftBuffer.Length, 1, (data, size) =>
                                                                                                               {
                                                                                                                   byte[] b = _leftBuffer;
                                                                                                                   System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
                                                                                                               });
            }
        }
    }
于 2012-12-19T19:16:32.960 回答