Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public override async Task<Sample> Import()
- {
- using (Stream Input = (await ImportTarget.OpenSequentialReadAsync()).AsStreamForRead())
- {
- // Create the decoder and get it's samples
- using (AudioDecoder Decoder = new AudioDecoder(Input))
- {
- IEnumerable<DataPointer> PointerSamples = Decoder.GetSamples();
- // Extract all the bytes from the sample pointers.
- List<byte> ByteData = new List<byte>();
- unsafe
- {
- foreach (DataPointer DP in PointerSamples)
- {
- void* Pointer = DP.Pointer.ToPointer();
- for (int j = 0; j < DP.Size; j++)
- {
- ByteData.Add(*((byte*)Pointer + j));
- }
- }
- }
- // Convert the bytes to float values
- int BitDepth = Decoder.WaveFormat.BitsPerSample;
- int CurrentIndex = 0;
- Func<float> ConvertFunc = null;
- switch (BitDepth)
- {
- case 8:
- ConvertFunc = () => (sbyte)ByteData[CurrentIndex++];
- break;
- case 16:
- ConvertFunc = () =>
- {
- byte[] Buffer = new byte[2];
- Buffer[0] = ByteData[CurrentIndex++];
- Buffer[1] = ByteData[CurrentIndex++];
- return BitConverter.ToInt16(Buffer, 0);
- };
- break;
- case 24:
- ConvertFunc = () =>
- {
- byte[] Buffer = new byte[4];
- Buffer[1] = ByteData[CurrentIndex++];
- Buffer[2] = ByteData[CurrentIndex++];
- Buffer[3] = ByteData[CurrentIndex++];
- return BitConverter.ToInt32(Buffer, 0);
- };
- break;
- case 32:
- ConvertFunc = () =>
- {
- byte[] Buffer = new byte[4];
- Buffer[0] = ByteData[CurrentIndex++];
- Buffer[1] = ByteData[CurrentIndex++];
- Buffer[2] = ByteData[CurrentIndex++];
- Buffer[3] = ByteData[CurrentIndex++];
- return BitConverter.ToSingle(Buffer, 0);
- };
- break;
- default:
- throw new NotSupportedException("Bitdepths other than 8, 16, 24 and 32 are not supported");
- }
- float[] Samples = new float[ByteData.Count / (BitDepth / 8)];
- float MaxValue = 0;
- for (int i = 0; i < Samples.Length; i++)
- {
- Samples[i] = ConvertFunc();
- MaxValue = Math.Max(MaxValue, Math.Abs(Samples[i]));
- }
- // Normalize all values
- for (int i = 0; i < Samples.Length; i++)
- {
- Samples[i] /= MaxValue;
- }
- // Return my own sample
- return new LoadedSample(Samples, new AudioEncodingProperties() { Bitrate = (uint)Decoder.WaveFormat.AverageBytesPerSecond * 8, BitsPerSample = (uint)Decoder.WaveFormat.BitsPerSample, ChannelCount = (uint)Decoder.WaveFormat.Channels, SampleRate = (uint)Decoder.WaveFormat.SampleRate });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment