.Net 如何直接播放音频样本
Posted
技术标签:
【中文标题】.Net 如何直接播放音频样本【英文标题】:.Net How to play audio samples directly 【发布时间】:2012-12-19 18:43:58 【问题描述】:我有通过 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)
【问题讨论】:
我对@987654321@ 的回答将使用NAudio 播放文件。 【参考方案1】:首先,您需要实现IWaveProvider
或使用NAudio 附带的IWaveProvider
实现之一,例如WaveProvider16
。接下来,使用WaveOut.Init(IWaveProvider Provider)
使用IWaveProvider
初始化WaveOut
对象,最后调用WaveOut.Play()
。
【讨论】:
【参考方案2】:是的,我找到了解决方案: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);
);
【讨论】:
以上是关于.Net 如何直接播放音频样本的主要内容,如果未能解决你的问题,请参考以下文章
有没有一种简单的方法来设置核心音频回调来访问播放背景音频的样本?