static void TestRaw()
        {
            using (var vorbis = new NVorbis.VorbisReader(@"..\..\..\TestFiles\2test.ogg"))
            using (var outFile = System.IO.File.Create(@"..\..\..\TestFiles\2test.wav"))
            using (var writer = new System.IO.BinaryWriter(outFile))
            {
                writer.Write(Encoding.ASCII.GetBytes("RIFF"));
                writer.Write(0);
                writer.Write(Encoding.ASCII.GetBytes("WAVE"));
                writer.Write(Encoding.ASCII.GetBytes("fmt "));
                writer.Write(18);
                writer.Write((short)1); // PCM format
                writer.Write((short)vorbis.Channels);
                writer.Write(vorbis.SampleRate);
                writer.Write(vorbis.SampleRate * vorbis.Channels * 2);  // avg bytes per second
                writer.Write((short)(2 * vorbis.Channels)); // block align
                writer.Write((short)16); // bits per sample
                writer.Write((short)0); // extra size

                writer.Write(Encoding.ASCII.GetBytes("data"));
                writer.Flush();
                var dataPos = outFile.Position;
                writer.Write(0);

                var buf = new float[vorbis.SampleRate / 10 * vorbis.Channels];
                int count;
                while ((count = vorbis.ReadSamples(buf, 0, buf.Length)) > 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        var temp = (int)(32767f * buf[i]);
                        if (temp > 32767)
                        {
                            temp = 32767;
                        }
                        else if (temp < -32768)
                        {
                            temp = -32768;
                        }
                        writer.Write((short)temp);
                    }
                }
                writer.Flush();

                writer.Seek(4, System.IO.SeekOrigin.Begin);
                writer.Write((int)(outFile.Length - 8L));

                writer.Seek((int)dataPos, System.IO.SeekOrigin.Begin);
                writer.Write((int)(outFile.Length - dataPos - 4L));

                writer.Flush();
            }
        }
Example #2
0
        public OggDecoder(byte[] data)
        {
            var stream = new System.IO.MemoryStream(data);
            Reader = new NVorbis.VorbisReader(stream, true);

            if (Reader.Channels == 1)
                Format = Audio.Format.Mono16;
            else
                Format = Audio.Format.Stereo16;

            Frequency = Reader.SampleRate;
            IsStreamingPrefered = Reader.TotalTime.TotalSeconds > 10.0f;
        }
Example #3
0
        /**
         * Reads an OGG audio clip and converts it to *.raw file
         * */
        public static void ConvertOggToRAW(String srcoggfile, String dstrawfile)
        {
            srcoggfile = Path.GetFullPath(srcoggfile);
            dstrawfile = Path.GetFullPath(dstrawfile);

            Debug.Log("[CSLMusic] Convert " + srcoggfile + " to " + dstrawfile);

            try
            {

                using (var vorbis = new NVorbis.VorbisReader(srcoggfile))
                {
                    using (var fileStream = new FileStream(dstrawfile, FileMode.Create))
                    {
                        //NVorbis data
                        int channels = vorbis.Channels;
                        int sampleRate = vorbis.SampleRate;
                        var duration = vorbis.TotalTime;

                        if(channels != 2 || sampleRate != 44100)
                        {
                            Debug.LogError("[CSLMusic] Error: Input file " + srcoggfile + " must have 2 channels and 44100Hz sample rate!");

                            //Add to list
                            //ConversionManager.Info_NonConvertedFiles.Add(srcoggfile);
                            return;
                        }

                        var buffer = new float[16384];
                        int count;

                        //From SavWav
                        Int16[] intData = new Int16[buffer.Length];
                        //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]

                        Byte[] bytesData = new Byte[buffer.Length * 2];
                        //bytesData array is twice the size of
                        //dataSource array because a float converted in Int16 is 2 bytes.

                        int rescaleFactor = 32767; //to convert float to Int16

                        while ((count = vorbis.ReadSamples(buffer, 0, buffer.Length)) > 0)
                        {
                            // Do stuff with the samples returned...
                            // Sample value range is -0.99999994f to 0.99999994f
                            // Samples are interleaved (chan0, chan1, chan0, chan1, etc.)

                            for (int i = 0; i<buffer.Length; i++)
                            {
                                intData[i] = (short)(buffer[i] * rescaleFactor);
                                Byte[] byteArr = new Byte[2];
                                byteArr = BitConverter.GetBytes(intData[i]);
                                byteArr.CopyTo(bytesData, i * 2);
                            }

                            fileStream.Write(bytesData, 0, bytesData.Length);
                        }
                    }
                }

            }
            catch (InvalidDataException ex)
            {
                Debug.LogError("... ERROR: Could not read file! " + ex.Message);

                //Add to list
                //CSLMusicModSettings.Info_NonConvertedFiles.Add(srcoggfile);

                return;
            }

            Debug.Log("... done.");
        }
        public void Save(string path, Action<string, int, int> progressCallback = null)
        {
            lock (sync)
            {
                if (progressCallback != null) progressCallback("Validating file names...", 0, 0);

                // Validate file names for dupes
                List<string> names = new List<string>();

                // We're going to assume there is only one level of files
                foreach (PackageEntry entry in entries)
                {
                    string normalizedName = Path.GetFileName(entry.Name).ToLowerInvariant();
                    if (names.Contains(normalizedName))
                        throw new InvalidOperationException(string.Format("Package contains multiple entries with the file name \"{0}\".", normalizedName));
                    names.Add(normalizedName);
                }

                PackageEntry manifestEntry = entries.Find(e => Path.GetFileName(e.Name) == "info.xml");
                if (manifestEntry != null)
                {
                    // Put manifest at the end of the file.
                    entries.Remove(manifestEntry);
                    entries.Add(manifestEntry);
                }
            }

            string tmpPath = Path.GetTempFileName();
            try
            {
                lock (sync)
                {
                    using (FileStream fs = File.Open(tmpPath, FileMode.Open, FileAccess.ReadWrite))
                    {
                        BinaryWriter bw = new BinaryWriter(fs);
                        BinaryReader br = new BinaryReader(packStream);

                        // Calculate starting offset
                        if (progressCallback != null) progressCallback("Preparing to save...", 0, 0);
                        long currOffset = 4;
                        foreach (PackageEntry entry in entries)
                        {
                            currOffset += 20 + Encoding.Unicode.GetByteCount(Path.GetFileName(entry.Name));
                        }

                            fs.SetLength(currOffset);
                            fs.Seek(currOffset, SeekOrigin.Begin);

                            // Copy data
                            int i = 0;
                            List<PackageEntry> newEntries = new List<PackageEntry>();
                            foreach (PackageEntry entry in entries)
                            {
                                if (progressCallback != null) progressCallback(string.Format("Copying {0}", entry.Name), i, entries.Count);
                                if (entry.Offset == -1)
                                {
                                    PackageEntry addEntry = new PackageEntry { Name = Path.GetFileName(entry.Name) };
                                    addEntry.Length = (int)new FileInfo(entry.Name).Length;
                                    addEntry.Offset = fs.Position;

                                    if (Path.GetExtension(entry.Name).ToLowerInvariant() == ".ogg")
                                    {
                                        using (NVorbis.VorbisReader vorb = new NVorbis.VorbisReader(entry.Name))
                                        {
                                            addEntry.SampleLength = (float)vorb.TotalTime.TotalSeconds;
                                        }
                                    }
                                    else
                                    {
                                        addEntry.SampleLength = 0;
                                    }

                                    newEntries.Add(addEntry);
                                    bw.Write(File.ReadAllBytes(entry.Name));
                                }
                                else
                                {
                                    newEntries.Add(new PackageEntry { Name = entry.Name, Length = entry.Length, Offset = fs.Position, SampleLength = entry.SampleLength });
                                    packStream.Seek(entry.Offset, SeekOrigin.Begin);
                                    bw.Write(br.ReadBytes(entry.Length));
                                }
                                ++i;
                            }

                            // Write header
                            if (progressCallback != null) progressCallback("Writing file table...", entries.Count, entries.Count);
                            fs.Seek(0, SeekOrigin.Begin);
                            bw.Write(newEntries.Count);

                            foreach (PackageEntry entry in newEntries)
                            {
                                byte[] nameBytes = Encoding.Unicode.GetBytes(entry.Name);
                                bw.Write(nameBytes.Length);
                                bw.Write(nameBytes);
                                bw.Write(entry.Length);
                                bw.Write(entry.Offset);
                                bw.Write(entry.SampleLength);
                            }

                        fs.Flush();
                        fs.Seek(0, SeekOrigin.Begin);

                        // Final copy to original
                        packStream.Close();
                        packStream = File.Open(path, FileMode.Create, FileAccess.ReadWrite);
                        if (progressCallback != null) progressCallback("Finalizing...", entries.Count, entries.Count);
                        fs.CopyTo(packStream);
                    }
                }

                Load();
            }
            finally
            {
                File.Delete(tmpPath);
            }
        }
Example #5
0
        public VorbisWaveReader(System.IO.Stream sourceStream)
        {
            _reader = new NVorbis.VorbisReader(sourceStream, false);

            _waveFormat = NAudio.Wave.WaveFormat.CreateIeeeFloatWaveFormat(_reader.SampleRate, _reader.Channels);
        }
Example #6
0
        public VorbisWaveReader(string fileName)
        {
            _reader = new NVorbis.VorbisReader(fileName);

            _waveFormat = NAudio.Wave.WaveFormat.CreateIeeeFloatWaveFormat(_reader.SampleRate, _reader.Channels);
        }
Example #7
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && _reader != null)
            {
                _reader.Dispose();
                _reader = null;
            }

            base.Dispose(disposing);
        }
Example #8
0
 public bool Decode(Stream stream)
 {
     NVorbis.VorbisReader vorbis = new NVorbis.VorbisReader(stream, true);
     float[] buffer = new float[1024];
     List<byte> result = new List<byte>();
     int count;
     while ((count = vorbis.ReadSamples(buffer, 0, buffer.Length)) > 0)
     {
         for (int i = 0; i < count; i++)
         {
             short temp = (short)(32767f * buffer[i]);
             if (temp > 32767)
             {
                 result.Add(0xFF);
                 result.Add(0x7F);
             }
             else if (temp < -32768)
             {
                 result.Add(0x80);
                 result.Add(0x00);
             }
             result.Add((byte)temp);
             result.Add((byte)(temp >> 8));
         }
     }
     this.Channels = (ushort)vorbis.Channels;
     this.SamplesPerSecond = (uint)vorbis.SampleRate;
     this.Data = result.ToArray();
     return true;
 }