如何把内存波形从声卡播放
看了几个stackoverflow 的帖子,试验成功如下:
引用 NAudio
//引用
using NAudio.Wave;
//全局申请波形播放变量
WaveOut _waveOut = new WaveOut(); //播放器对象
IWaveProvider provider; //播放流提供者
byte[] dataByte; //播放波形 Int16平铺成Byte
//取得波形
//假设波形长度 sizeByte/2, 你已经读取到dataInt16
short[] dataInt16 = new short[sizeByte / 2];
dataByte = new byte[sizeByte];
Buffer.BlockCopy(dataInt16, 0, dataByte, 0, (int) sizeByte);
//初始化播放器
//初始化流提供者
provider = new RawSourceWaveStream(new MemoryStream(dataByte), new WaveFormat(11025, 1));
_waveOut.Init(provider); //初始化媒体播放
//播放
_waveOut.Play();
//停止
_waveOut.Stop();
//停止后初始化流, 不然等同于Pause
provider = new RawSourceWaveStream(new MemoryStream(dataByte), new WaveFormat(11025, 1));
_waveOut.Init(provider);
//暂停
_waveOut.Pause();
当然, 上面的播放、停止、暂停都是事件响应哦,不要真的拷贝在一起运行啊。
感谢
- 主体播放方法:
https://stackoverflow.com/questions/28792548/how-can-i-play-byte-array-of-audio-raw-data-using-naudio - Int16 - Byte拷贝:
https://stackoverflow.com/questions/7152034/convert-short-to-stream-which-can-be-played-as-audio
另一个方法是用MS自己的MediaPlayer
https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.mediaplayer?view=netframework-4.8
一时半会儿搞不定,不讲了。
有个链接,但是看上去就不完整:
https://stackoverflow.com/questions/6340967/play-wav-mp3-from-memory
完整可工作代码
C# 代码, Form控件请脑补, 需要用JYTek SeeSharp Tools的EasyChartX
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NAudio.Wave;
using System.IO;
namespace StudyNAudio
{
public partial class Form1 : Form
{
//波形播放变量
WaveOut _waveOut = new WaveOut(); //播放器对象
IWaveProvider provider; //播放流提供者
byte[] dataByte; //播放波形 Int16平铺成Byte
public Form1()
{
InitializeComponent();
}
private void buttonLoad_Click(object sender, EventArgs e)
{
var reader = new Mp3FileReader(textBoxFileName.Text);
MemoryStream memStream = new MemoryStream();
WaveFileWriter.WriteWavFileToStream(memStream, reader);
BinaryReader br = new BinaryReader(memStream, Encoding.UTF8);
long sizeByte = memStream.Length-memStream.Position;
short[] dataInt16 = new short[sizeByte / 2];
dataByte = new byte[sizeByte];
for (int i = 0; i < dataInt16.Length; i++)
{
dataInt16[i] = br.ReadInt16();
}
Buffer.BlockCopy(dataInt16, 0, dataByte, 0, (int) sizeByte);
easyChartX1.Plot(dataInt16);
//初始化流提供者
provider = new RawSourceWaveStream(new MemoryStream(dataByte), new WaveFormat(11025, 1));
_waveOut.Init(provider); //初始化媒体播放
}
private void buttonPlay_Click(object sender, EventArgs e)
{
_waveOut.Play();
}
private void buttonStop_Click(object sender, EventArgs e)
{
_waveOut.Stop();
//停止后初始化流, 不然等同于Pause
provider = new RawSourceWaveStream(new MemoryStream(dataByte), new WaveFormat(11025, 1));
_waveOut.Init(provider);
}
private void buttonPause_Click(object sender, EventArgs e)
{
_waveOut.Pause();
}
}
}