gpt4 book ai didi

c# - 将 short[] 转换为可以作为音频播放的 Stream

转载 作者:行者123 更新时间:2023-11-30 13:33:33 25 4
gpt4 key购买 nike

所以我有一个 short[] 数组,它表示 WAV 文件的原始数据。这意味着它不包含通常包含的任何页眉或页脚信息。为了播放这段音频,我需要将它转换成某种流,不幸的是这个 short[] 数组中的数据是 Int16 并且许多值超过 255,因此无法转换为字节,也无法转换为溪流。有谁知道我将如何播放这些音频数据?

最佳答案

您可以将短数组转换回字节数组:

short[] sampleData = ...
byte[] byteArray = new byte[sampleData.Length*2];
Buffer.BlockCopy(sampleData , 0, byteArray, 0, byteArray.Length);

然后您可以使用下面的 WaveMemoryStream 类创建波形流 - 为此您需要知道示例数据的波形格式。然后可以将该流保存为 WAV 文件或由 SoundPlayer 播放。 .

public class WaveMemoryStream : Stream
{
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override bool CanRead { get { return true; } }
public override long Length { get { return _waveStream.Length; } }
public override long Position { get { return _waveStream.Position; } set { _waveStream.Position = value; } }

private MemoryStream _waveStream;

public WaveMemoryStream(byte[] sampleData, int audioSampleRate, ushort audioBitsPerSample, ushort audioChannels)
{
_waveStream = new MemoryStream();
WriteHeader(_waveStream, sampleData.Length, audioSampleRate, audioBitsPerSample, audioChannels);
WriteSamples(_waveStream, sampleData);
_waveStream.Position = 0;
}

public void WriteHeader(Stream stream, int length, int audioSampleRate, ushort audioBitsPerSample, ushort audioChannels)
{
BinaryWriter bw = new BinaryWriter(stream);

bw.Write(new char[4] { 'R', 'I', 'F', 'F' });
int fileSize = 36 + length;
bw.Write(fileSize);
bw.Write(new char[8] { 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ' });
bw.Write((int)16);
bw.Write((short)1);
bw.Write((short)audioChannels);
bw.Write(audioSampleRate);
bw.Write((int)(audioSampleRate * ((audioBitsPerSample * audioChannels) / 8)));
bw.Write((short)((audioBitsPerSample * audioChannels) / 8));
bw.Write((short)audioBitsPerSample);

bw.Write(new char[4] { 'd', 'a', 't', 'a' });
bw.Write(length);
}

public void WriteSamples(Stream stream, byte[] sampleData)
{
BinaryWriter bw = new BinaryWriter(stream);
bw.Write(sampleData, 0, sampleData.Length);
}

public override int Read(byte[] buffer, int offset, int count)
{
return _waveStream.Read(buffer, offset, count);
}

public virtual void WriteTo(Stream stream)
{
int bytesRead = 0;
byte[] buffer = new byte[8192];

do
{
bytesRead = Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);

stream.Flush();
}

public override void Flush()
{
_waveStream.Flush();
}

public override long Seek(long offset, SeekOrigin origin)
{
return _waveStream.Seek(offset, origin);
}

public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}

关于c# - 将 short[] 转换为可以作为音频播放的 Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7152034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com