public override void Read(string fileIn) { BinaryReader br = new BinaryReader(File.OpenRead(fileIn)); nscr = new sNSCR(); // Generic header nscr.header.id = br.ReadChars(4); nscr.header.endianess = br.ReadUInt16(); if (nscr.header.endianess == 0xFFFE) nscr.header.id.Reverse<char>(); nscr.header.constant = br.ReadUInt16(); nscr.header.file_size = br.ReadUInt32(); nscr.header.header_size = br.ReadUInt16(); nscr.header.nSection = br.ReadUInt16(); // Read section nscr.nrcs.id = br.ReadChars(4); nscr.nrcs.section_size = br.ReadUInt32(); nscr.nrcs.width = br.ReadUInt16(); nscr.nrcs.height = br.ReadUInt16(); nscr.nrcs.padding = br.ReadUInt32(); nscr.nrcs.data_size = br.ReadUInt32(); nscr.nrcs.mapData = new NTFS[nscr.nrcs.data_size / 2]; for (int i = 0; i < nscr.nrcs.mapData.Length; i++) nscr.nrcs.mapData[i] = Actions.MapInfo(br.ReadUInt16()); br.Close(); Set_Map(nscr.nrcs.mapData, true, nscr.nrcs.width, nscr.nrcs.height); }
protected void LoadDirectoriesFromStream( BinaryReader reader ) { Directories = new List<DirectoryEntry>(); while( reader.PeekChar() != INT_RecordSeparator ) { var entry = CreateDirectoryObject(); char[] buffer = reader.ReadChars( Leader.SizeFieldTag ); string tag = new string( buffer ); if( tag == "0000" ) entry.Tag = DirectoryDataType.Filename; else if( tag == "0001" ) entry.Tag = DirectoryDataType.DDFRecordIdentifier; else entry.Tag = (DirectoryDataType)Enum.Parse( typeof( DirectoryDataType ), tag ); if( entry.Tag == DirectoryDataType.Unknown ) throw new InvalidDataException( String.Format("Unknown tag {0}", tag) ); buffer = reader.ReadChars( Leader.SizeFieldLength ); entry.Length = int.Parse( new string( buffer ) ); buffer = reader.ReadChars( Leader.SizeFieldPos ); entry.Position = int.Parse( new string( buffer ) ); Directories.Add( entry ); } reader.Read(); }
public static TileSet ReadFromFile(string fileName) { var data = ZFile.ReadFile(fileName); if (data == null) return null; var reader = new BinaryReader(new MemoryStream(data)); var tileSet = new TileSet(null); tileSet.Signature = new string(reader.ReadChars(4)); tileSet.Version = new string(reader.ReadChars(4)); tileSet.ColorDepth = (BitsPerColor)reader.ReadByte(); tileSet.ExtendedOptions = ZMath.GetBool(reader.ReadByte()); var tileDataSize = reader.ReadByte(); // maybe can be check for some conditions? var nameLength = reader.ReadByte(); var tilesCount = reader.ReadInt32(); tileSet.Name = new string(reader.ReadChars(64), 0, nameLength); for (int i = 0; i < tilesCount; i++) { try { tileSet.Add(new Tile(reader.ReadUInt64())); } catch { return null; } } return tileSet; }
public FruaGameData GetGameData() { var data = new FruaGameData(); using (var stream = new FileStream(_fullPath, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(stream)) { data.Name = new string(reader.ReadChars(32)).RemoveNulls(); data.StartingXp = reader.ReadInt32(); data.StartingPp = reader.ReadInt32(); data.StartingGems = reader.ReadInt32(); data.StartingJewelry = reader.ReadInt32(); data.StartingModule = reader.ReadByte(); data.StartingTown = reader.ReadByte(); data.StartingEquipment = reader.ReadByte(); reader.ReadByte(); // unused or unknown byte for (int i = 0; i < 8; i++) { data.Keys.Add(new string(reader.ReadChars(16)).RemoveNulls()); } for (int i = 0; i < 12; i++) { data.Items.Add(new string(reader.ReadChars(16)).RemoveNulls()); } data.Password = new string(reader.ReadChars(15)).RemoveNulls(); } } return data; }
public TextureArchive[] ReadTextures(BinaryReader pacStream) { int nfiles = pacStream.ReadInt32(); pacStream.ReadBytes(12); //The rest of the header. Not important... var textures = new TextureArchive[nfiles]; for (var i = 0; i < nfiles; i++) { var texture = new TextureArchive(); texture.alignedstring = new string(pacStream.ReadChars(16)); texture.extension = new string(pacStream.ReadChars(4)); texture.size = pacStream.ReadInt32(); texture.offset = pacStream.ReadInt32(); pacStream.ReadBytes(4); var pos = pacStream.BaseStream.Position; pacStream.BaseStream.Position = texture.offset; texture.stream = pacStream.ReadBytes(texture.size); pacStream.BaseStream.Position = pos; textures[i] = texture; } return textures; }
/// <summary> /// Creates a new entity that was embedded next in the stream /// </summary> /// <param name="stream">The System.IO.BinaryReader to use.</param> public Entity(BinaryReader stream) { X = stream.ReadInt16(); Y = stream.ReadInt16(); Layer = stream.ReadInt16(); Scripts = new List<string>(); Type = (EntityType)stream.ReadInt16(); stream.ReadBytes(8); short len; if (Type == EntityType.Person) { len = stream.ReadInt16(); Name = new string(stream.ReadChars(len)); len = stream.ReadInt16(); Spriteset = new string(stream.ReadChars(len)); int scripts = stream.ReadInt16(); // read the person script data for (int i = 0; i < scripts; ++i) { len = stream.ReadInt16(); Scripts.Add(new string(stream.ReadChars(len))); } stream.ReadBytes(16); // reserved } else { len = stream.ReadInt16(); Function = new string(stream.ReadChars(len)); Trigger = new CompiledMethod(Program._engine, Function); } }
/// <summary> /// Creates a new entity that was embedded next in the stream /// </summary> /// <param name="stream">The System.IO.BinaryReader to use.</param> public Entity(BinaryReader stream) { X = stream.ReadInt16(); Y = stream.ReadInt16(); Layer = stream.ReadInt16(); Scripts = new List<string>(); Type = (EntityType)stream.ReadInt16(); stream.ReadBytes(8); short len; if (Type == EntityType.Person) { len = stream.ReadInt16(); Name = new string(stream.ReadChars(len)); len = stream.ReadInt16(); Spriteset = new string(stream.ReadChars(len)); int scripts = stream.ReadInt16(); // read the person script data for (int i = 0; i < scripts; ++i) { len = stream.ReadInt16(); Scripts.Add(new string(stream.ReadChars(len))); } stream.ReadBytes(16); // reserved _graphic = new Bitmap(Properties.Resources.person); } else { len = stream.ReadInt16(); Function = new string(stream.ReadChars(len)); _graphic = new Bitmap(Properties.Resources.trigger); } }
private UserHeaderLabel ReadUHL(BinaryReader br) { char[] header = br.ReadChars(4); if (new string(header) != "UHL1") throw new Exception("Wrong UHL header"); UserHeaderLabel uhl = new UserHeaderLabel(); uhl.Longitude = ReadGeoAngle(br, 3, 2); uhl.Latitude = ReadGeoAngle(br, 3, 2); uhl.LonInterval = ReadInterval(br); uhl.LatInterval = ReadInterval(br); char[] accuracy = br.ReadChars(4); char[] classification = br.ReadChars(3); char[] uniqueRef = br.ReadChars(12); uhl.Accuracy = new string(accuracy); uhl.Classification = new string(classification); uhl.UniqueRef = new string(uniqueRef); uhl.LongitudeLines = ReadInt(br, 4); uhl.LatitudePoints = ReadInt(br, 4); uhl.MultipleAccuracy = br.ReadChar() == '1'; char[] reserved = br.ReadChars(24); return uhl; }
public FsaNajka(Stream stream, bool leaveOpen = false) { using (var file = new BinaryReader(stream, Encoding.UTF8, leaveOpen)) { if (new string(file.ReadChars(4)) != "@naj") throw new Exception("Invalid header"); if (file.ReadByte() != 1) throw new Exception("Invalid version"); _type = file.ReadByte(); _id2Char = file.ReadChars(file.ReadByte()); _tree = file.ReadBytes((int)(file.BaseStream.Length - file.BaseStream.Position)); } _id2ConvertedChar = new char[4][]; _id2ConvertedChar[0] = _id2Char; _id2ConvertedChar[1] = new char[_id2Char.Length]; _id2ConvertedChar[2] = new char[_id2Char.Length]; _id2ConvertedChar[3] = new char[_id2Char.Length]; for (var i = 0; i < _id2Char.Length; i++) { _id2ConvertedChar[1][i] = char.ToLowerInvariant(_id2Char[i]); _id2ConvertedChar[2][i] = _id2Char[i].RemoveDiacritics(); _id2ConvertedChar[3][i] = char.ToLowerInvariant(_id2ConvertedChar[2][i]); } _nodePrefix = SinkTo(0, '!'); _nodePostfix = SinkTo(0, '^'); }
public void Load(string destinationDirectory, string resourceName, BinaryReader binaryReader) { var start = binaryReader.BaseStream.Position; uint totalLength = binaryReader.ReadUInt32(); var container = new string(binaryReader.ReadChars(4)); switch (container) { case "FORM": case "RIFF": uint length = binaryReader.ReadUInt32(); // this is probably not really a length, with values like 0xcccccccc var header = new string(binaryReader.ReadChars(4)); switch (header) { case "XMID": case "XDIR": new XMidiLoader().Load(destinationDirectory, resourceName, binaryReader, totalLength); break; case "WAVE": break; } break; default: // Possibly a WAV but without a header binaryReader.BaseStream.Seek(start, SeekOrigin.Begin); new WaveLoader().Load(destinationDirectory, resourceName, binaryReader, (int)totalLength, true); break; } }
public BIF_KEY(String filename) { BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open)); signature = br.ReadChars(4); version = br.ReadChars(4); FILETABLE_ENTRIES = br.ReadUInt32(); KEYTABLE_ENTRIES = br.ReadUInt32(); br.ReadBytes(4); FILETABLE_OFFSET = br.ReadUInt32(); KEYTABLE_OFFSET = br.ReadUInt32(); BUILD_YEAR += br.ReadUInt32(); BUILD_DAY = br.ReadUInt32(); // MessageBox.Show(this+""); br.BaseStream.Seek(FILETABLE_OFFSET, SeekOrigin.Begin); for (int i = 0; i < FILETABLE_ENTRIES; i++) { FILETABLE.Add(new BIF_FILETABLE_ENTRY(br)); } br.BaseStream.Seek(KEYTABLE_OFFSET, SeekOrigin.Begin); for (int i = 0; i < KEYTABLE_ENTRIES; i++) { BIF_KEYTABLE_ENTRY key = new BIF_KEYTABLE_ENTRY(br); FILETABLE[(int)key.ResourceIdx].ownedResources.Add(key); } br.Close(); }
public wavefile(FileStream file) { BinaryReader binRead = new BinaryReader(file); //head data ChunkID = binRead.ReadChars(4); ChunkSize = binRead.ReadInt32(); Format = binRead.ReadChars(4); Subchunk1ID = binRead.ReadChars(4); Subchunk1Size = binRead.ReadInt32();//in bytes AudioFormat = binRead.ReadInt16(); NumChannels = binRead.ReadInt16(); SampleRate = binRead.ReadInt32();//samples per second? ByteRate = binRead.ReadInt32(); BlockAlign = binRead.ReadInt16(); BitsPerSample = binRead.ReadInt16(); Subchunk2ID = binRead.ReadChars(4); Subchunk2Size = binRead.ReadInt32();//in bytes int numSamples = Subchunk2Size / (BitsPerSample / 8); data = new byte[numSamples]; wave = new float[numSamples]; data = binRead.ReadBytes(numSamples); for (int i = 0; i < numSamples; i++) { wave[i] = ((float)data[i] - 128) / 128; } }
//------------------------------------------------------------------------------- private static void ReadPrintDataRec(short i, BinaryReader f, StreamWriter log) { short id; char[] code = new char[3]; char[] name = new char[17]; char[] continent = new char[11]; char[] region = new char[10]; int surfaceArea; short yearOfIndep; long population; float lifeExp; int gnp; id = f.ReadInt16(); code = f.ReadChars(3); name = f.ReadChars(17); continent = f.ReadChars(11); region = f.ReadChars(10); surfaceArea = f.ReadInt32(); yearOfIndep = f.ReadInt16(); population = f.ReadInt64(); lifeExp = f.ReadSingle(); gnp = f.ReadInt32(); if (id == 0) log.WriteLine("[{0:000}] EMPTY SPOT", i); else log.WriteLine("[{0:000}] {1:000}|{2}|{3}|{4}|{5}|" + "{6,10:N0}|{7,5}|{8,13:N0}|{9,4:N1}|{10,9:N0}|", i, id, new string(code), new string(name), new string(continent), new string(region), surfaceArea, yearOfIndep, population, lifeExp, gnp); }
/// <summary> /// Constructor /// </summary> /// <param name="file">Path to the DBM module to open.</param> public DbmReader(string file) { using (var dbm = new BinaryReader(File.OpenRead(file))) { // Header HeaderID = new string(dbm.ReadChars(4)); // Skip to module name. Also cut off any padded bytes. dbm.BaseStream.Position = 0x10; string modName = new string(dbm.ReadChars(44)); ModuleName = modName.Substring(0, modName.LastIndexOf('\0')); // Number of instruments. dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 8; // + 8 is to skip over the chunk name and length indicators. NumInstruments = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16(); // Number of samples dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 10; NumSamples = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16(); // Number of songs. dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 12; NumSongs = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16(); // Number of patterns dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 14; NumPatterns = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16(); // Number of channels dbm.BaseStream.Position = NameChunkOffset + NameChunkSize + 16; NumChannels = BitConverter.IsLittleEndian ? dbm.ReadInt16()>>8 : dbm.ReadInt16(); } }
/// <summary> /// Constructor /// </summary> /// <param name="path">Path to the PSF file</param> public PsfReader(string path) { using (var fs = new BinaryReader(File.OpenRead(path))) { // Header ID HeaderID = new string(fs.ReadChars(3)); // Skip version byte (don't care) fs.BaseStream.Position += 1; // Reserved area length and compressed data length int resLen = fs.ReadInt32(); int dataLen = fs.ReadInt32(); // CRC32 of the data CRC32 = fs.ReadUInt32(); // Skip those lengths, we don't read any of this. fs.BaseStream.Position += (resLen + dataLen); // Check if we have any metadata, and read it if we do. bool endOfStream = (fs.BaseStream.Position == fs.BaseStream.Length); if (!endOfStream && new string(fs.ReadChars(5)) == "[TAG]") { // Now read in the metadata this.tag = new string(fs.ReadChars((int)(fs.BaseStream.Length - fs.BaseStream.Position))); // Check for "_lib[n]" tags ReferencedLibs = ParseIncludedLibs(); // Actual tag metadata Artist = GetInfo("artist="); Game = GetInfo("game="); SongTitle = GetInfo("title="); Genre = GetInfo("genre="); Copyright = GetInfo("copyright="); Year = GetInfo("year="); Comment = GetInfo("comment="); XSFRipper = GetXSFRipper(path); Volume = GetInfo("volume="); Length = GetInfo("length="); FadeLength = GetInfo("fade="); } else { Artist = "N/A"; Game = "N/A"; SongTitle = "N/A"; Genre = "N/A"; Copyright = "N/A"; Year = "N/A"; Comment = "N/A"; XSFRipper = "N/A"; Volume = "N/A"; Length = "N/A"; FadeLength = "N/A"; } } }
/// <summary> /// Constructor /// </summary> /// <param name="path">Path to an IT module</param> public ITReader(string path) { using (var br = new BinaryReader(File.OpenRead(path))) { HeaderID = new string(br.ReadChars(4)); SongName = new string(br.ReadChars(26)); PatternHighlightInfo = br.ReadInt16(); // Totals TotalOrders = br.ReadInt16(); TotalInstruments = br.ReadInt16(); TotalSamples = br.ReadInt16(); TotalPatterns = br.ReadInt16(); // Tracker related CreatedWithTracker = br.ReadInt16(); CompatibleWithTracker = br.ReadInt16(); // Flags short flag = br.ReadInt16(); IsStereo = ((flag & 1) != 0); HasVol0MixOptimizations = ((flag & 2) != 0); UsesInstruments = ((flag & 4) != 0); SlideType = ((flag & 8) != 0) ? SlideTypes.Linear : SlideTypes.Amiga; UsesOldEffects = ((flag & 16) != 0); LinkEffectMemory = ((flag & 32) != 0); UsesMidiPitchController = ((flag & 64) != 0); // Special flags short special = br.ReadInt16(); HasSongMessage = ((special & 1) != 0); // Volume and Tempo related stuff GlobalVolume = br.ReadByte(); MixVolume = br.ReadByte(); InitialSpeed = br.ReadByte(); InitialTempo = br.ReadByte(); PanningSeparation = br.ReadByte(); PitchWheelDepth = br.ReadByte(); // Song message short messageLen = br.ReadInt16(); int messageOffset = br.ReadInt32(); br.BaseStream.Position = messageOffset; if (HasSongMessage) SongMessage = new string(br.ReadChars(messageLen)).Replace((char) 0xD, '\n'); else SongMessage = "N/A"; // Channel related TotalUsedChannels = GetTotalUsedChannels(br); ChannelPanning = GetChannelPanning(br); ChannelVolumes = GetChannelVolumes(br); // Parsing ParseInstruments(br); ParseSamples(br); } }
public override void Read(string fileIn) { nclr = new sNCLR(); BinaryReader br = new BinaryReader(File.OpenRead(fileIn)); // Generic header nclr.header.id = br.ReadChars(4); nclr.header.endianess = br.ReadUInt16(); if (nclr.header.endianess == 0xFFFE) nclr.header.id.Reverse<char>(); nclr.header.constant = br.ReadUInt16(); nclr.header.file_size = br.ReadUInt32(); nclr.header.header_size = br.ReadUInt16(); nclr.header.nSection = br.ReadUInt16(); // PLTT section TTLP pltt = new TTLP(); pltt.ID = br.ReadChars(4); pltt.length = br.ReadUInt32(); pltt.depth = (ColorFormat)br.ReadUInt16(); pltt.unknown1 = br.ReadUInt16(); pltt.unknown2 = br.ReadUInt32(); pltt.pal_length = br.ReadUInt32(); if (pltt.pal_length == 0 || pltt.pal_length > pltt.length) pltt.pal_length = pltt.length - 0x18; uint colors_startOffset = br.ReadUInt32(); pltt.num_colors = (uint)((pltt.depth == ColorFormat.colors16) ? 0x10 : 0x100); if (pltt.pal_length / 2 < pltt.num_colors) pltt.num_colors = pltt.pal_length / 2; pltt.palettes = new Color[pltt.pal_length / (pltt.num_colors * 2)][]; br.BaseStream.Position = 0x18 + colors_startOffset; for (int i = 0; i < pltt.palettes.Length; i++) pltt.palettes[i] = Actions.BGR555ToColor(br.ReadBytes((int)pltt.num_colors * 2)); nclr.pltt = pltt; // PMCP section if (nclr.header.nSection == 1 || br.BaseStream.Position >= br.BaseStream.Length) goto End; PMCP pmcp = new PMCP(); pmcp.ID = br.ReadChars(4); pmcp.blockSize = br.ReadUInt32(); pmcp.unknown1 = br.ReadUInt16(); pmcp.unknown2 = br.ReadUInt16(); pmcp.unknown3 = br.ReadUInt32(); pmcp.first_palette_num = br.ReadUInt16(); nclr.pmcp = pmcp; End: br.Close(); Set_Palette(pltt.palettes, pltt.depth, true); }
protected void Read(Stream stream) { BinaryReader rdr = new BinaryReader(stream); Next = (IntPtr) rdr.ReadInt32(); IpAddress = new string(rdr.ReadChars(0x10)).TrimEnd('\0'); IpMask = new string(rdr.ReadChars(0x10)).TrimEnd('\0'); Context = rdr.ReadUInt32(); }
public GFFHeader(BinaryReader file) { _magicNumber = new String(file.ReadChars(4)); _versionNumber = new String(file.ReadChars(4)); _targetPlatform = new String(file.ReadChars(4)); _fileType = new String(file.ReadChars(4)); _fileVersion = new String(file.ReadChars(4)); _structCount = file.ReadUInt32(); _dataOffset = file.ReadUInt32(); }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("usage: wavextract <filename>"); return; } BinaryReader reader; try { reader = new BinaryReader(new FileStream(args[0], FileMode.Open), Encoding.ASCII); } catch (FileNotFoundException e) { Console.WriteLine("file not found."); return; } Directory.CreateDirectory("wav_output"); int num_files = 0; while (true) { try { long position = reader.BaseStream.Position; if (reader.ReadByte() != 0x52 || new string(reader.ReadChars(3)) != "IFF") continue; int chunk_size = reader.ReadInt32(); if (new string(reader.ReadChars(4)) == "WAVE") { reader.BaseStream.Position = position; byte[] wav = reader.ReadBytes(chunk_size + 8); Console.WriteLine("output/{0}.wav", position.ToString("X")); BinaryWriter writer = new BinaryWriter(new FileStream(@"wav_output\" + position.ToString("X") + ".wav", FileMode.Create), Encoding.ASCII); num_files++; writer.Write(wav); writer.Flush(); writer.Close(); } } catch (EndOfStreamException) { if (num_files == 0) { Directory.Delete("wav_output"); } Console.WriteLine("Done! extracted {0} files", num_files); return; } } }
public virtual void Read(BinaryReader stream) { // Read the data. id = new string(stream.ReadChars(9)); version = new string(stream.ReadChars(6)); dataMode = stream.ReadChar(); bitFormat = new string(stream.ReadChars(2)); // Skip past the pad and newline, 14 chars. stream.ReadChars(14); }
public WavAudioSource(Stream file, bool streaming = true) { Streaming = streaming; _fileStream = file; _reader = new BinaryReader(file); if (new string(_reader.ReadChars(4)) != "RIFF") throw new InvalidDataException("Specified stream is not a wave file."); int chunkSize = _reader.ReadInt32(); if (new string(_reader.ReadChars(4)) != "WAVE") throw new InvalidDataException("Specified stream is not a wave file"); if (new string(_reader.ReadChars(4)) != "fmt ") throw new NotSupportedException("Specified wave format is not supported."); _formatChunkSize = _reader.ReadInt32(); _audioFormat = _reader.ReadInt16(); if (_audioFormat != 1) throw new NotSupportedException("Compressed WAV files are not supported."); _numChannels = _reader.ReadInt16(); _sampleRate = _reader.ReadInt32(); _byteRate = _reader.ReadInt32(); _blockAlign = _reader.ReadInt16(); _bitsPerSample = _reader.ReadInt16(); if (new string(_reader.ReadChars(4)) != "data") throw new InvalidDataException("Specified wave format is not supported."); _dataChunkSize = _reader.ReadInt32(); if(_numChannels == 2) { if (_bitsPerSample == 8) _alFormat = ALFormat.Stereo8; else _alFormat = ALFormat.Stereo16; } else { if (_bitsPerSample == 8) _alFormat = ALFormat.Mono8; else _alFormat = ALFormat.Mono16; } _dataStart = (int)_reader.BaseStream.Position; if (!Streaming) _data = _reader.ReadBytes((int)_reader.BaseStream.Length); }
public string ReadBuffer() { using (BinaryReader reader = new BinaryReader(StreamWAV)) { Header.FileTypeID = reader.ReadChars(4); if (!Header.FileTypeID.SequenceEqual("RIFF")) { Passed = false; return "Format non conforme du fichier"; } Header.FileLenght = reader.ReadInt32(); Header.MediaTypedID = reader.ReadChars(8); if (!Header.MediaTypedID.SequenceEqual("WAVEfmt ")) { Passed = false; return "Format non conforme du fichier"; } Header.ChunkSizeFormat = reader.ReadInt32(); Header.FormatTag = Math.Abs(reader.ReadInt16()); Header.Channels = reader.ReadInt16(); Header.Frequency = reader.ReadInt32(); Header.AverageBytesPerSec = reader.ReadInt32(); Header.BlockAlign = reader.ReadInt16(); Header.BitsPerSample = reader.ReadInt16(); if (Header.ChunkSizeFormat > 16) { int ExtraSize = reader.ReadInt16(); var ExtraData = reader.ReadBytes(ExtraSize); } Header.ChunkIDData = reader.ReadChars(4); if (!Header.ChunkIDData.SequenceEqual("data")) { Passed = false; return "Format non conforme du fichier"; } Header.ChunkSizeData = reader.ReadInt32(); Buffer = reader.ReadBytes(Header.ChunkSizeData); reader.Close(); Passed = true; StreamWAV.Close(); return "Analyse du fichier réussi"; } }
/* Lifted from example code in OpenTK * See: https://github.com/opentk/opentk/blob/develop/Source/Examples/OpenAL/1.1/Playback.cs */ private static byte[] LoadWave(Stream stream, out int channels, out int bits, out int rate) { if (stream == null) { throw new ArgumentNullException("stream"); } using (BinaryReader reader = new BinaryReader(stream)) { // RIFF header string signature = new string(reader.ReadChars(4)); if (signature != "RIFF") throw new NotSupportedException("Specified stream is not a wave file."); /*int riff_chunck_size = */ reader.ReadInt32(); string format = new string(reader.ReadChars(4)); if (format != "WAVE") throw new NotSupportedException("Specified stream is not a wave file."); // WAVE header string format_signature = new string(reader.ReadChars(4)); if (format_signature != "fmt ") throw new NotSupportedException("Specified wave file is not supported."); /* int format_chunk_size = */ reader.ReadInt32(); /* int audio_format = */ reader.ReadInt16(); int num_channels = reader.ReadInt16(); int sample_rate = reader.ReadInt32(); /* int byte_rate = */ reader.ReadInt32(); /* int block_align = */ reader.ReadInt16(); int bits_per_sample = reader.ReadInt16(); string data_signature = new string(reader.ReadChars(4)); if (data_signature != "data") throw new NotSupportedException("Specified wave file is not supported."); /* int data_chunk_size = */ reader.ReadInt32(); channels = num_channels; bits = bits_per_sample; rate = sample_rate; return reader.ReadBytes((int)reader.BaseStream.Length); } }
public WaveFile(Stream stream) { if (stream == null) throw new ArgumentNullException ("s"); var reader = new BinaryReader (stream); //RIFF check if (new String (reader.ReadChars (4)) != "RIFF") new InvalidDataException ("Not a RIFF format file."); int riff_chunk_size = reader.ReadInt32 (); //WAVE check if (new String (reader.ReadChars (4)) != "WAVE") new InvalidDataException ("Not a WAVE format file."); //FMT check if (new String (reader.ReadChars (4)) != "fmt ") new InvalidDataException ("Doesn't have fmt chunk."); int format_chunk_size = reader.ReadInt32 (); int audio_format = reader.ReadInt16 (); int num_channels = reader.ReadInt16 (); int sample_rate = reader.ReadInt32 (); int byte_rate = reader.ReadInt32 (); int block_align = reader.ReadInt16 (); int bits_per_sample = reader.ReadInt16 (); //data check if (new String (reader.ReadChars (4)) != "data") new InvalidDataException ("Doesn't have data chunk"); int data_chunk_size = reader.ReadInt32(); this.channels = num_channels; this.bps = bits_per_sample; this.SampleRate = sample_rate; this.HeaderSize = reader.BaseStream.Position; this.DataBinary = reader; switch (channels) { case 1: this.SoundFormat = this.bps == 8 ? ALFormat.Mono8 : ALFormat.Mono16; break; case 2: this.SoundFormat = this.bps == 8 ? ALFormat.Stereo8 : ALFormat.Stereo16; break; default: throw new NotSupportedException ("The specified sound format is not supported."); } }
public bool Read(BinaryReader BR) { try { this.Flag_ = BR.ReadByte(); if (this.Flag_ != 0x91 && this.Flag_ != 0xA1 && this.Flag_ != 0xB1) { // Accuracy unknown this.Clear(); return false; } // Assumes that BR is set to ASCII encoding this.Category_ = new string(BR.ReadChars(8)).TrimEnd(' '); this.ID_ = new string(BR.ReadChars(8)).TrimEnd(' '); // Read BITMAPINFO structure length if (BR.ReadUInt32() != 40) { this.Clear(); return false; } // Read BITMAPINFO structure this.Width_ = BR.ReadInt32(); this.Height_ = BR.ReadInt32(); this.Planes_ = BR.ReadUInt16(); this.BitCount_ = BR.ReadUInt16(); this.Compression_ = BR.ReadUInt32(); this.ImageSize_ = BR.ReadUInt32(); this.HorizontalResolution_ = BR.ReadUInt32(); this.VerticalResolution_ = BR.ReadUInt32(); this.UsedColors_ = BR.ReadUInt32(); this.ImportantColors_ = BR.ReadUInt32(); // Sanity check on the values in the structure if (this.Width_ < 0 || this.Width_ > 16 * 1024 || this.Height_ < 0 || this.Height_ > 16 * 1024 || this.Planes_ != 1) { this.Clear(); return false; } if (this.Flag_ == 0xA1) // Assume DirectX texture { this.ReadDXT(BR); } else if (this.Flag_ == 0x91 || this.Flag_ == 0xB1) // Bitmap { this.ReadBitmap(BR); } } catch { this.Clear(); } return (this.Image_ != null); }
protected void Read(Stream stream) { BinaryReader rdr = new BinaryReader(stream); HostName = new string(rdr.ReadChars(MAX_HOSTNAME_LEN + 4)).TrimEnd('\0'); DomainName = new string(rdr.ReadChars(MAX_DOMAIN_NAME_LEN + 4)).TrimEnd('\0'); CurrentDnsServer = (IntPtr) rdr.ReadInt32(); DnsServerList.Add(new IpAddrString(stream));//TODO: get the rest of the servers in the list too NodeType = rdr.ReadUInt32(); ScopeId = new string(rdr.ReadChars(MAX_SCOPE_ID_LEN + 4)).TrimEnd('\0'); EnableRouting = rdr.ReadUInt32(); EnableProxy = rdr.ReadUInt32(); EnableDns = rdr.ReadUInt32(); }
public static WavFile ReadFile(string fileName) { // // Using .WAV file format from https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ // WavFile wf = new WavFile(); using (BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read))) { char[] id = br.ReadChars(4); if (!id.SequenceEqual(new char[] { 'R', 'I', 'F', 'F' })) throw new FormatException("Missing RIFF header"); br.ReadUInt32(); // chunk size id = br.ReadChars(4); if (!id.SequenceEqual(new char[] { 'W', 'A', 'V', 'E' })) throw new FormatException("Only WAVE format currently supported"); id = br.ReadChars(4); if (!id.SequenceEqual(new char[] { 'f', 'm', 't', ' ' })) throw new FormatException("Missing 'fmt ' sub-chunk"); int size = (int)br.ReadUInt32(); // sub-chunk size if (size != 16) throw new FormatException("Unexpected format size"); wf.AudioFormat = br.ReadUInt16(); wf.NumChannels = br.ReadUInt16(); wf.SampleRate = br.ReadUInt32(); wf.ByteRate = br.ReadUInt32(); wf.BlockAlign = br.ReadUInt16(); wf.BitsPerSample = br.ReadUInt16(); id = br.ReadChars(4); if (!id.SequenceEqual(new char[] { 'd', 'a', 't', 'a' })) throw new FormatException("Missing 'data' sub-chunk"); size = (int)br.ReadUInt32(); // sub-chunk size wf.Data = br.ReadBytes(size); } return wf; }
public static SoundBuffer Load(Stream s) { BinaryReader br = new BinaryReader(s); var magic = new String(br.ReadChars(4)); if (magic != "RIFF") throw new FormatException("Invalid WAV file"); UInt32 size = br.ReadUInt32(); var id = new String(br.ReadChars(4)); if (id != "WAVE") throw new FormatException("Invalid WAV file"); var fmtSig = new String(br.ReadChars(4)); if (fmtSig != "fmt ") throw new FormatException("Format Chunk in WAV file not found"); var fmtChunckSize = br.ReadInt32(); var audioFormat = br.ReadInt16(); var channels = br.ReadInt16(); var sampleRate = br.ReadInt32(); var byteRate = br.ReadInt32(); var blockAlign = br.ReadInt16(); var bitsPerSample = br.ReadInt16(); ; var dataSig = new String(br.ReadChars(4)); if (dataSig != "data") { throw new FormatException("Data chunk in WAV file not found"); } var dataChunckSize = br.ReadInt32(); var data = br.ReadBytes(dataChunckSize); OpenTK.Audio.OpenAL.ALFormat format; if (channels == 1 && bitsPerSample == 8) format = OpenTK.Audio.OpenAL.ALFormat.Mono8; else if (channels == 1 && bitsPerSample == 16) format = OpenTK.Audio.OpenAL.ALFormat.Mono16; else if (channels == 2 && bitsPerSample == 8) format = OpenTK.Audio.OpenAL.ALFormat.Stereo8; else if (channels == 2 && bitsPerSample == 16) format = OpenTK.Audio.OpenAL.ALFormat.Stereo16; else throw new Exception("Unsupported audio format"); SoundBuffer sb = new SoundBuffer(); sb.BufferData(data, format, sampleRate); return sb; }
public int getWafeFormat(BinaryReader br) { UInt32 sz = findChunk(true, "hdrl", br.BaseStream.Length, br); if (sz ==0) throw new Exception("AVI header not found"); int res = -1; int cstream = 0; long epos=br.BaseStream.Position+sz; while(br.BaseStream.Position<epos && res==-1) { string s = new String(br.ReadChars(4)); sz = br.ReadUInt32(); long x=br.BaseStream.Position+sz; if (s == "LIST") { s = new String(br.ReadChars(4)); if (s == "strl") { long xx = br.BaseStream.Position; UInt32 xsz = findChunk(false, "strh", br.BaseStream.Position + sz, br); if (xsz >0) { s = new string(br.ReadChars(4)); if (s == "auds") { br.BaseStream.Position = xx; xsz = findChunk(false, "strf", br.BaseStream.Position + sz, br); if (xsz==16) { UInt16 fmt=br.ReadUInt16(); if (fmt != 1) throw new Exception("Unknown wave format"); wf.FormatTag = WaveFormatTag.Pcm; wf.Channels = br.ReadInt16(); wf.SamplesPerSecond = br.ReadInt32(); wf.AverageBytesPerSecond = br.ReadInt32(); wf.BlockAlign = br.ReadInt16(); wf.BitsPerSample = br.ReadInt16(); res = cstream; } } } cstream++; } } br.BaseStream.Position = x; } return res; }