本文整理汇总了C#中NAudio.Wave.WaveChannel32.Read方法的典型用法代码示例。如果您正苦于以下问题:C# WaveChannel32.Read方法的具体用法?C# WaveChannel32.Read怎么用?C# WaveChannel32.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NAudio.Wave.WaveChannel32
的用法示例。
在下文中一共展示了WaveChannel32.Read方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LoadFile
public void LoadFile()
{
var wave = new WaveChannel32(new Mp3FileReader(@"file.mp3"));
var buffer = new byte[16384*2];
var read = 0;
var i = 0;
while (wave.Position < wave.Length)
{
read = wave.Read(buffer, 0, 16384*2);
var max = 0f;
var absMax = 0f;
for (int j = 0; j < read / 4; j++)
{
var s = BitConverter.ToSingle(buffer, j*4);
var abs = Math.Abs(s);
if (abs > absMax)
{
absMax = abs;
max = s;
}
}
Samples.Add(new TLSample(i += 2, max));
}
}
示例2: AudioSample
public AudioSample(string fileName)
{
_fileName = fileName;
WaveFileReader reader = new WaveFileReader(fileName);
//offsetStream = new WaveOffsetStream(reader);
//channelStream = new WaveChannel32(offsetStream);
channelStream = new WaveChannel32(reader);
muted = false;
volume = 1.0f;
#region ReverseStuff
//Code to reverse
NAudioBufferReverse nbr = new NAudioBufferReverse();
reversedSample = new byte[(int)channelStream.Length];
channelStream.Read(reversedSample, 0, (int)channelStream.Length);
bytesPerSample = (channelStream.WaveFormat.BitsPerSample / 8) * channelStream.WaveFormat.Channels;
reversedSample = nbr.reverseSample(reversedSample, (int)channelStream.Length, bytesPerSample);
#endregion
}
示例3: ShowChart
// Non-public methods
private void ShowChart()
{
this.Chart.Series.RemoveAt(0);
Series series = this.Chart.Series.Add("wave");
series.ChartType = SeriesChartType.FastLine;
series.ChartArea = "ChartArea1";
WaveChannel32 wave = new WaveChannel32(this.Reader);
while (wave.Position < wave.Length)
{
int bytes = 100000;
byte[] buffer = new byte[bytes];
int read = wave.Read(buffer, 0, bytes);
double total = 0;
int count = 0;
double average = 0;
for (int i = 0; i < read / 4; i++)
{
double x = BitConverter.ToSingle(buffer, i * 4);
double z = average * count;
double diff = Math.Abs(z - total);
if (diff > 0.00001)
throw new Exception("no");
total += x;
count += 1;
average = (z + x) / count;
}
series.Points.Add(total / Convert.ToDouble(count));
}
}
示例4: waveformGenerateWorker_DoWork
private void waveformGenerateWorker_DoWork(object sender, DoWorkEventArgs e)
{
WaveformGenerationParams waveformParams = e.Argument as WaveformGenerationParams;
Mp3FileReader waveformMp3Stream = new Mp3FileReader(waveformParams.Path);
WaveChannel32 waveformInputStream = new WaveChannel32(waveformMp3Stream);
waveformInputStream.Sample += waveStream_Sample;
int frameLength = fftDataSize;
int frameCount = (int)((double)waveformInputStream.Length / (double)frameLength);
int waveformLength = frameCount * 2;
byte[] readBuffer = new byte[frameLength];
waveformAggregator = new SampleAggregator(frameLength);
float maxLeftPointLevel = float.MinValue;
float maxRightPointLevel = float.MinValue;
int currentPointIndex = 0;
float[] waveformCompressedPoints = new float[waveformParams.Points];
List<float> waveformData = new List<float>();
List<int> waveMaxPointIndexes = new List<int>();
for (int i = 1; i <= waveformParams.Points; i++)
{
waveMaxPointIndexes.Add((int)Math.Round(waveformLength * ((double)i / (double)waveformParams.Points), 0));
}
int readCount = 0;
while (currentPointIndex * 2 < waveformParams.Points && waveformInputStream.Position < (waveformInputStream.Length - 1024))
{
waveformInputStream.Read(readBuffer, 0, readBuffer.Length);
waveformData.Add(waveformAggregator.LeftMaxVolume);
waveformData.Add(waveformAggregator.RightMaxVolume);
if (waveformAggregator.LeftMaxVolume > maxLeftPointLevel)
maxLeftPointLevel = waveformAggregator.LeftMaxVolume;
if (waveformAggregator.RightMaxVolume > maxRightPointLevel)
maxRightPointLevel = waveformAggregator.RightMaxVolume;
if (readCount > waveMaxPointIndexes[currentPointIndex])
{
waveformCompressedPoints[(currentPointIndex * 2)] = maxLeftPointLevel;
waveformCompressedPoints[(currentPointIndex * 2) + 1] = maxRightPointLevel;
maxLeftPointLevel = float.MinValue;
maxRightPointLevel = float.MinValue;
currentPointIndex++;
}
if (readCount % 3000 == 0)
{
float[] clonedData = (float[])waveformCompressedPoints.Clone();
App.Current.Dispatcher.Invoke(new Action(() =>
{
WaveformData = clonedData;
}));
}
if (waveformGenerateWorker.CancellationPending)
{
e.Cancel = true;
break;
}
readCount++;
}
float[] finalClonedData = (float[])waveformCompressedPoints.Clone();
App.Current.Dispatcher.Invoke(new Action(() =>
{
fullLevelData = waveformData.ToArray();
WaveformData = finalClonedData;
}));
waveformInputStream.Close();
waveformInputStream.Dispose();
waveformInputStream = null;
waveformMp3Stream.Close();
waveformMp3Stream.Dispose();
waveformMp3Stream = null;
}
示例5: btnBrowse_Click
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog oFD1 = new OpenFileDialog();
oFD1.Multiselect = true;
if (oFD1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
files = oFD1.SafeFileNames; //Save only the names
paths = oFD1.FileNames; //Save the full paths
for (int i = 0; i < files.Length; i++)
{
//listBox1.Items.Add(files[i]); //Add songs to the listbox
ext = Path.GetExtension(oFD1.FileName);
if (ext == ".avi")
{
//Convert Avi to wav
AviManager aviManager = new AviManager(oFD1.FileName, true);
AudioStream audioStream = aviManager.GetWaveStream();
audioStream.ExportStream(oFD1.FileName + ".wav");
filepath = oFD1.FileName + ".wav";
aviManager.Close();
listBox1.Items.Add(files[i]); //Add songs to the listbox
}
else if (ext == ".wav")
{
filepath = oFD1.FileName;
listBox1.Items.Add(files[i]); //Add songs to the listbox
}
}
}
NAudio.Wave.WaveChannel32 wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(filepath));
WaveFileReader wavFile = new WaveFileReader(filepath);
byte[] mainBuffer = new byte[wave.Length];
float fileSize = (float)wavFile.Length / 1048576;
if (fileSize < 2)
window = 8;
else if (fileSize > 2 && fileSize < 4)
window = 16;
else if (fileSize > 4 && fileSize < 8)
window = 32;
else if (fileSize > 8 && fileSize < 12)
window = 128;
else if (fileSize > 12 && fileSize < 20)
window = 256;
else if (fileSize > 20 && fileSize < 30)
window = 512;
else
window = 2048;
float[] fbuffer = new float[mainBuffer.Length / window];
wave.Read(mainBuffer, 0, mainBuffer.Length);
for (int i = 0; i < fbuffer.Length; i++)
{
fbuffer[i] = (BitConverter.ToSingle(mainBuffer, i * window));
}
double time = wave.TotalTime.TotalSeconds;
GraphPane myPane1 = zedGraphControl2.GraphPane;
PointPairList list1 = new PointPairList();
PointPairList list2 = new PointPairList();
for (int i = 0; i < fbuffer.Length; i++)
{
list1.Add(i, fbuffer[i]);
}
list2.Add(0, 0);
list2.Add(time, 0);
if (myCurve1 != null && myCurve2 != null)
{
myCurve1.Clear();
myCurve2.Clear();
}
GraphPane myPane2 = zedGraphControl2.GraphPane;
myPane2.Title.Text = "Audio Sound Wave";
myPane2.XAxis.Title.Text = "Time, Seconds";
myPane2.YAxis.Title.Text = "Sound Wave Graph";
myCurve1 = myPane1.AddCurve(null, list1, System.Drawing.Color.Blue, SymbolType.None);
myCurve1.IsX2Axis = true;
myCurve2 = myPane1.AddCurve(null, list2, System.Drawing.Color.Black, SymbolType.None);
myPane1.XAxis.Scale.MaxAuto = true;
myPane1.XAxis.Scale.MinAuto = true;
//Threshold Line
double threshHoldY = -1.2;
double threshHoldX = 1.2;
LineObj threshHoldLine = new LineObj(System.Drawing.Color.Red, myPane2.XAxis.Scale.Min, threshHoldY, myPane2.XAxis.Scale.Max, threshHoldY);
LineObj threshHoldLine2 = new LineObj(System.Drawing.Color.Red, myPane2.XAxis.Scale.Min, threshHoldX, myPane2.XAxis.Scale.Max, threshHoldX);
myPane2.GraphObjList.Add(threshHoldLine);
myPane2.GraphObjList.Add(threshHoldLine2);
// Add a text box with instructions
TextObj text = new TextObj(
"Ratio Conversion: 1:100\nRed Lines: Threshold\nZoom: left mouse & drag\nContext Menu: right mouse",
0.05f, 0.95f, CoordType.ChartFraction, AlignH.Left, AlignV.Bottom);
text.FontSpec.StringAlignment = StringAlignment.Near;
myPane2.GraphObjList.Add(text);
// Show the x axis grid
//.........这里部分代码省略.........
示例6: waveformGenerateWorker_DoWork
private void waveformGenerateWorker_DoWork(object sender, DoWorkEventArgs e)
{
var waveformParams = (WaveformGenerationParams)e.Argument;
float[] waveformDataFromCache;
if (waveformDataCache.TryGet(waveformParams.Path, out waveformDataFromCache))
{
Application.Current.Dispatcher.Invoke(() => WaveformData = waveformDataFromCache);
return;
}
Mp3FileReader waveformMp3Stream = new Mp3FileReader(waveformParams.Path);
WaveChannel32 waveformInputStream = new WaveChannel32(waveformMp3Stream);
waveformInputStream.Sample += waveStream_Sample;
int frameLength = fftDataSize;
int frameCount = (int)((double)waveformInputStream.Length / (double)frameLength);
int waveformLength = frameCount * 2;
byte[] readBuffer = new byte[frameLength];
waveformAggregator = new SampleAggregator(frameLength);
float maxLeftPointLevel = float.MinValue;
float maxRightPointLevel = float.MinValue;
int currentPointIndex = 0;
float[] waveformCompressedPoints = new float[waveformParams.Points];
List<float> waveformData = new List<float>();
List<int> waveMaxPointIndexes = new List<int>();
for (int i = 1; i <= waveformParams.Points; i++)
{
waveMaxPointIndexes.Add((int)Math.Round(waveformLength * ((double)i / (double)waveformParams.Points), 0));
}
int readCount = 0;
while (currentPointIndex * 2 < waveformParams.Points)
{
waveformInputStream.Read(readBuffer, 0, readBuffer.Length);
waveformData.Add(waveformAggregator.LeftMaxVolume);
waveformData.Add(waveformAggregator.RightMaxVolume);
if (waveformAggregator.LeftMaxVolume > maxLeftPointLevel)
maxLeftPointLevel = waveformAggregator.LeftMaxVolume;
if (waveformAggregator.RightMaxVolume > maxRightPointLevel)
maxRightPointLevel = waveformAggregator.RightMaxVolume;
if (readCount > waveMaxPointIndexes[currentPointIndex])
{
waveformCompressedPoints[(currentPointIndex * 2)] = maxLeftPointLevel;
waveformCompressedPoints[(currentPointIndex * 2) + 1] = maxRightPointLevel;
maxLeftPointLevel = float.MinValue;
maxRightPointLevel = float.MinValue;
currentPointIndex++;
}
if (readCount % 3000 == 0)
{
float[] clonedData = (float[])waveformCompressedPoints.Clone();
try
{
App.Current.Dispatcher.Invoke(new Action(() =>
{
WaveformData = clonedData;
}));
}
catch (TaskCanceledException)
{
e.Cancel = true;
return;
}
}
if (waveformGenerateWorker.CancellationPending)
{
e.Cancel = true;
break;
}
readCount++;
}
float[] finalClonedData = (float[])waveformCompressedPoints.Clone();
// Don't cache half-finished waveforms (my CDJ-1000MK3s do this...)
if (!waveformGenerateWorker.CancellationPending)
waveformDataCache.Add(waveformParams.Path, finalClonedData);
App.Current.Dispatcher.Invoke(new Action(() =>
{
fullLevelData = waveformData.ToArray();
WaveformData = finalClonedData;
}));
waveformInputStream.Close();
waveformInputStream.Dispose();
waveformInputStream = null;
waveformMp3Stream.Close();
waveformMp3Stream.Dispose();
waveformMp3Stream = null;
}
示例7: LoadSound
private void LoadSound(WaveChannel32 sound, int index)
{
int count = 0;
int read = 0;
sound.Sample += Sound0_Sample;
bufferSize =1024* sampleRate * 16 / 256000*Channels ;
byte[] buffer = new byte[bufferSize];
while (sound.Position < sound.Length)
{
max =-1;
min = 1;
read = sound.Read(buffer, 0, bufferSize);
pwfc.WaveFormDisplay.AddValue(max, min);
count++;
}
sound.Close();
wfr.Close();
Debug.WriteLine("Sound is " + sound.TotalTime.TotalMilliseconds + "ms long");
Debug.WriteLine("Sound is " + wfr.Length + " bytes");
Debug.WriteLine("Called addvalue " + count + " times");
}
示例8: worker_DoWork
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
Mp3FileReader reader = new Mp3FileReader(FileName);
WaveChannel32 channel = new WaveChannel32(reader);
channel.Sample += new EventHandler<SampleEventArgs>(channel_Sample);
int points = 2000;
int frameLength = (int)FFTDataSize.FFT2048;
int frameCount = (int)((double)channel.Length / (double)frameLength);
int waveformLength = frameCount * 2;
byte[] readBuffer = new byte[frameLength];
float maxLeftPointLevel = float.MinValue;
float maxRightPointLevel = float.MinValue;
int currentPointIndex = 0;
float[] waveformCompressedPoints = new float[points];
List<float> waveformData = new List<float>();
List<int> waveMaxPointIndexes = new List<int>();
for (int i = 1; i <= points; i++)
{
waveMaxPointIndexes.Add((int)Math.Round(waveformLength * ((double)i / (double)points), 0));
}
int readCount = 0;
while (currentPointIndex * 2 < points)
{
channel.Read(readBuffer, 0, readBuffer.Length);
waveformData.Add(InputSampler.LeftMax);
waveformData.Add(InputSampler.RightMax);
if (InputSampler.LeftMax > maxLeftPointLevel)
maxLeftPointLevel = InputSampler.LeftMax;
if (InputSampler.RightMax > maxRightPointLevel)
maxRightPointLevel = InputSampler.RightMax;
if (readCount > waveMaxPointIndexes[currentPointIndex])
{
waveformCompressedPoints[(currentPointIndex * 2)] = maxLeftPointLevel;
waveformCompressedPoints[(currentPointIndex * 2) + 1] = maxRightPointLevel;
maxLeftPointLevel = float.MinValue;
maxRightPointLevel = float.MinValue;
currentPointIndex++;
}
if (readCount % 3000 == 0)
{
WaveformData = (float[])waveformCompressedPoints.Clone();
}
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
readCount++;
}
FullLevelData = waveformData.ToArray();
WaveformData = (float[])waveformCompressedPoints.Clone();
// Cleanup
channel.Close();
channel.Dispose();
channel = null;
reader.Close();
reader.Dispose();
reader = null;
}
示例9: StopRecord_Click
//Кнопка остановки записи и вывода осциллограмы посредством элемента управления Microsoft Chart
private void StopRecord_Click(object sender, EventArgs e)
{
timer1.Stop();
// если переменная от DirectSoundOut не налл, то останавливаем воспроизведение
if (_waveOut != null)
{
_waveOut.Stop();
}
// если переменная от WaveIn не налл, то останавливаем запись
if (_sourceStream != null)
{
_sourceStream.StopRecording();
}
// если переменная от WaveFileWriter не налл, то освобождаем ресурс, инициализируем наллом и строим осциллограму
if (_waveWriter != null)
{
StartRecord.Enabled = true;
_waveWriter.Dispose();
_waveWriter = null;
// Очищаем чарт для нового вывода осциллограмы
chart1.Series.Clear();
// Устанавливаем чарт
chart1.Series.Add("wave");
chart1.Series["wave"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine;
chart1.Series["wave"].ChartArea = "ChartArea1";
chart1.ChartAreas[0].AxisY.Interval = 0.1;
// WaveChannel32 представляет канал для WaveMixerStream, который может микшировать несколько 32 битовых потоков ввода (обычно используется с входных стереоканалов)
// Присваиваем переменную запоминающую путь сохранения .wav файла
WaveChannel32 waveChannel32 = new WaveChannel32(new WaveFileReader(_path));
//размер буффера
var buffer = new byte[3916384];
// Перебор текущей позиции что будет длится по всей длине поступаемого потока с waveChannel32
while (waveChannel32.Position < waveChannel32.Length)
{
//bytesread = waveChannel32.Read(Читает байты из потока; Cмещение в буфере; Количество считанных байтов)
var read = waveChannel32.Read(buffer, 0, 3916384);
//chart time-magnitude
for (var i = 0; i < read / 4; i++)
{
chart1.Series["wave"].Points.Add(BitConverter.ToSingle(buffer, i * 4));
_volumeLeft = (BitConverter.ToSingle(buffer, i * 4));
i++;
_volumeRight = (BitConverter.ToSingle(buffer, i * 4));
if (_volumeLeft > 0.5f && _volumeRight > 0.5f)
{
_ampLeft.Add(_volumeLeft); //Добавляем в массив левый канал
_ampRigh.Add(_volumeRight); //Добавляем в массив правый канал
_counter.Add(i / (2 * 44.1)); //Добавляем в массив время
}
}
}
for (int i = 0; i < _ampLeft.Count; i++)
{
//начинаем порядковый номер с 1
int number = i + 1;
//создаем элемент
ListViewItem list = new ListViewItem(number.ToString("00"));
//добавляем в listview
list.SubItems.Add(_ampLeft[i].ToString());
list.SubItems.Add(_ampRigh[i].ToString());
double a = Convert.ToDouble(_counter[i].ToString());
list.SubItems.Add(string.Format("{00:00:000}", a));
listView1.Items.Add(list);
}
// для отделения значений разных записей
ListViewItem list2 = new ListViewItem();
list2.SubItems.Add(" ");
list2.SubItems.Add(" ");
listView1.Items.Add(list2);
// Освободжаем waveChannel32
waveChannel32.Dispose();
}
}
示例10: soundAnalysis
private void soundAnalysis()
{
NAudio.Wave.WaveChannel32 wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(vfilepath));
WaveFileReader wavFile = new WaveFileReader(vfilepath);
byte[] mainBuffer = new byte[wave.Length];
float fileSize = (float)wavFile.Length / 1048576;
if (fileSize < 2)
window = 8;
else if (fileSize > 2 && fileSize < 4)
window = 16;
else if (fileSize > 4 && fileSize < 8)
window = 32;
else if (fileSize > 8 && fileSize < 12)
window = 128;
else if (fileSize > 12 && fileSize < 20)
window = 256;
else if (fileSize > 20 && fileSize < 30)
window = 512;
else
window = 2048;
float[] fbuffer = new float[mainBuffer.Length / window];
wave.Read(mainBuffer, 0, mainBuffer.Length);
for (int i = 0; i < fbuffer.Length; i++)
{
fbuffer[i] = (BitConverter.ToSingle(mainBuffer, i * window));
}
double time = wave.TotalTime.TotalSeconds;
ZedGraphControl zedGraphControl2 = new ZedGraphControl();
GraphPane myPane1 = zedGraphControl2.GraphPane;
PointPairList list1 = new PointPairList();
PointPairList list2 = new PointPairList();
for (int i = 0; i < fbuffer.Length; i++)
{
list1.Add(i, fbuffer[i]);
}
list2.Add(0, 0);
list2.Add(time, 0);
if (myCurve1 != null && myCurve2 != null)
{
myCurve1.Clear();
myCurve2.Clear();
}
GraphPane myPane2 = zedGraphControl2.GraphPane;
myPane2.Title.Text = "Audio Sound Wave";
myPane2.XAxis.Title.Text = "Time, Seconds";
myPane2.YAxis.Title.Text = "Sound Wave Graph";
myCurve1 = myPane1.AddCurve(null, list1, System.Drawing.Color.Blue, SymbolType.None);
myCurve1.IsX2Axis = true;
myCurve2 = myPane1.AddCurve(null, list2, System.Drawing.Color.Black, SymbolType.None);
myPane1.XAxis.Scale.MaxAuto = true;
myPane1.XAxis.Scale.MinAuto = true;
//Threshold Line
double threshHoldY = -1.2;
double threshHoldX = 1.2;
LineObj threshHoldLine = new LineObj(System.Drawing.Color.Red, myPane2.XAxis.Scale.Min, threshHoldY, myPane2.XAxis.Scale.Max, threshHoldY);
LineObj threshHoldLine2 = new LineObj(System.Drawing.Color.Red, myPane2.XAxis.Scale.Min, threshHoldX, myPane2.XAxis.Scale.Max, threshHoldX);
myPane2.GraphObjList.Add(threshHoldLine);
myPane2.GraphObjList.Add(threshHoldLine2);
// Add a text box with instructions
TextObj text = new TextObj(
"Ratio Conversion: 1:100\nRed Lines: Threshold\nZoom: left mouse & drag\nContext Menu: right mouse",
0.05f, 0.95f, CoordType.ChartFraction, AlignH.Left, AlignV.Bottom);
text.FontSpec.StringAlignment = StringAlignment.Near;
myPane2.GraphObjList.Add(text);
// Show the x axis grid
myPane2.XAxis.MajorGrid.IsVisible = true;
myPane2.YAxis.MajorGrid.IsVisible = true;
// Just manually control the X axis range so it scrolls continuously
// instead of discrete step-sized jumps
//myPane2.XAxis.Scale.Format = @"00:00:00";
myPane2.XAxis.Scale.IsSkipCrossLabel = true;
myPane2.XAxis.Scale.IsPreventLabelOverlap = true;
myPane2.XAxis.Type = ZedGraph.AxisType.Linear;
myPane2.XAxis.Scale.Min = 0;
myPane2.XAxis.Scale.Max = 1.2;
myPane2.AxisChange();
// turn off the opposite tics so the Y tics don't show up on the Y2 axis
myPane2.YAxis.MajorTic.IsOpposite = false;
myPane2.YAxis.MinorTic.IsOpposite = false;
// Don't display the Y zero line
myPane2.YAxis.MajorGrid.IsZeroLine = false;
// Align the Y axis labels so they are flush to the axis
myPane2.YAxis.Scale.Align = AlignP.Inside;
// Manually set the axis range
myPane2.YAxis.Scale.Min = -1.5;
myPane2.YAxis.Scale.Max = 1.5;
zedGraphControl2.AxisChange();
zedGraphControl2.Invalidate();
Bitmap graph = myPane1.GetImage();
//.........这里部分代码省略.........