Exemplo n.º 1
0
        public static SoundEffect Load(string path)
        {
            SoundEffect soundEffect;

            using (MemoryStream stream = new MemoryStream())
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    OggDecoder decoder = new OggDecoder();
                    decoder.Initialize(File.OpenRead(path));
                    byte[] data = decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray();
                    WriteWave(writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data);
                    stream.Position = 0;
                    soundEffect     = SoundEffect.FromStream(stream);
                }

            return(soundEffect);
        }
Exemplo n.º 2
0
        public static SoundEffect Convert(string path)
        {
            string      wavPath     = path.Replace(".ogg", ".wav");
            SoundEffect soundEffect = null;

            using (FileStream stream = new FileStream(wavPath, FileMode.Create))
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    OggDecoder decoder = new OggDecoder();
                    decoder.Initialize(File.OpenRead(path));
                    byte[] data = decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray();
                    WriteWave(writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data);
                }

            using (FileStream stream = new FileStream(wavPath, FileMode.Open))
                soundEffect = SoundEffect.FromStream(stream);

            return(soundEffect);
        }
Exemplo n.º 3
0
        public OggVorbisFile(string name, string filepath, Sound soundType)
        {
            Name = name;
            string cachefile = SystemInfo.DecodedMusicCache
                               + SystemInfo.PathSeparator.ToString ()
                               + soundType.ToString ()
                               + "_"
                               + name.GetHashCode ().ToString ()
                               + ".wav";

            Log.BlockList (id: 33, before: "  - ", after: "", begin: "Load ogg audio files:", end: "");
            Log.BlockList (id: 34, before: "  - ", after: "", begin: "Decode ogg audio files:", end: "");

            byte[] data;
            try {
                Log.ListElement (33, "[", soundType, "] ", name);
                data = File.ReadAllBytes (cachefile);
            }
            catch (Exception) {
                Log.ListElement (34, "[", soundType, "] ", name);
                OggDecoder decoder = new OggDecoder ();
                decoder.Initialize (TitleContainer.OpenStream (filepath));
                data = decoder.SelectMany (chunk => chunk.Bytes.Take (chunk.Length)).ToArray ();
                using (MemoryStream stream = new MemoryStream ())
                using (BinaryWriter writer = new BinaryWriter (stream)) {
                    WriteWave (writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data);
                    stream.Position = 0;
                    data = stream.ToArray ();
                }
                File.WriteAllBytes (cachefile, data);
            }

            using (MemoryStream stream = new MemoryStream (data)) {
                stream.Position = 0;
                SoundEffect soundEffect = SoundEffect.FromStream (stream);
                internalFile = new SoundEffectFile (name, soundEffect, soundType);
            }
        }
Exemplo n.º 4
0
        public static void CompileOggs(string path = null)
        {
            if (path == null)
            {
                path = Path.GetDirectoryName(Engine.Assembly.Location);
            }
            else if (path.StartsWith("."))
            {
                path = (Path.GetDirectoryName(Engine.Assembly.Location) + path.Substring(1));
            }
            if (!Directory.Exists(path))
            {
                return;
            }
            var files = Engine.DirSearch(path, ".ogg");

            foreach (var file in files)
            {
                var directoryName = Path.GetDirectoryName(file);
                var newFile       = (directoryName + "\\" + Path.GetFileNameWithoutExtension(file) + ".wav");
                if (File.Exists(newFile))
                {
                    continue;
                }
                using (var fs = new FileStream(newFile, FileMode.CreateNew))
                {
                    var decoder = new OggDecoder();
                    decoder.Initialize(new FileStream(file, FileMode.Open));
                    using (var bw = new BinaryWriter(fs))
                    {
                        WriteWave(bw, (decoder.Stereo ? 2 : 1), decoder.SampleRate, decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray());
                        bw.Close();
                    }
                    fs.Close();
                }
            }
        }
Exemplo n.º 5
0
        public SoundEffect Convert(string path)
        {
            string      wavPath     = path.Replace(".ogg", ".wav");
            SoundEffect soundEffect = null;
            int         c           = 0;
            Exception   le          = null;
            bool        done        = false;

            while (!done && c < ti)
            {
                FileStream stream = new FileStream(wavPath, FileMode.Create);
                try
                {
                    using (BinaryWriter writer = new BinaryWriter(stream))
                    {
                        OggDecoder decoder = new OggDecoder();
                        decoder.Initialize(File.OpenRead(path));
                        byte[] data = decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray();
                        WriteWave(writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data);
                    }
                }
                catch (Exception e)
                {
                    le = e;
                    c++;
                    Thread.Sleep(slp);
                }
                done = true;
                stream.Close();
                stream.Dispose();
            }


            int d = 0;

            while (soundEffect == null && d < ti)
            {
                FileStream stream = stream = new FileStream(wavPath, FileMode.Open);

                try
                {
                    soundEffect = SoundEffect.FromStream(stream);
                }
                catch (Exception e)
                {
                    le = e;
                    d++;
                    Thread.Sleep(slp);
                }

                stream.Close();
                stream.Dispose();
            }



            /*if(soundEffect == null)
             *  Monitor.Log(path + ":" + le.Message + ":" + le.StackTrace, LogLevel.Trace);*/


            return(soundEffect);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OggSharpSource" /> class.
        /// </summary>
        /// <param name="stream"><see cref="Stream" /> which contains raw waveform-audio data.</param>
        /// <param name="waveFormat">The format of the waveform-audio data within the <paramref name="stream" />.</param>
        /// <param name="chunks">the wave chunks read using the wavefile reader</param>
        public OggSharpSource(Stream stream, WaveFormat waveFormat, ReadOnlyCollection <WaveFileChunk> chunks)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (!stream.CanRead)
            {
                throw new ArgumentException("stream is not readable", "stream");
            }

            // format checking if the ogg is within a wav container
            if (waveFormat != null)
            {
                switch ((short)waveFormat.WaveFormatTag)
                {
                case 0x674f:     // OGG_VORBIS_MODE_1 "Og" Original stream compatible
                case 0x676f:     // OGG_VORBIS_MODE_1_PLUS "og" Original stream compatible
                case 0x6750:     // OGG_VORBIS_MODE_2 "Pg" Have independent header
                case 0x6770:     // OGG_VORBIS_MODE_2_PLUS "pg" Have independent headere
                case 0x6751:     // OGG_VORBIS_MODE_3 "Qg" Have no codebook header
                case 0x6771:     // OGG_VORBIS_MODE_3_PLUS "qg" Have no codebook header
                    break;

                default:
                    throw new ArgumentException(string.Format("Not supported encoding: {0}", waveFormat.WaveFormatTag));
                }
            }

            // format checking if the ogg is within a wav container
            if (chunks != null)
            {
                // check format
                var audioFormat = new AudioFormat();

                var fmtChunk = (FmtChunk)chunks.FirstOrDefault(x => x is FmtChunk);
                if (fmtChunk != null)
                {
                    // https://github.com/chirlu/sox/blob/4927023d0978615c74e8a511ce981cf4c29031f1/src/wav.c
                    long oldPosition   = stream.Position;
                    long startPosition = fmtChunk.StartPosition;
                    long endPosition   = fmtChunk.EndPosition;
                    long chunkDataSize = fmtChunk.ChunkDataSize;

                    stream.Position = startPosition;
                    var reader = new BinaryReader(stream);

                    audioFormat.Encoding              = (AudioEncoding)reader.ReadInt16();
                    audioFormat.Channels              = reader.ReadInt16();
                    audioFormat.SampleRate            = reader.ReadInt32();
                    audioFormat.AverageBytesPerSecond = reader.ReadInt32();
                    audioFormat.BlockAlign            = reader.ReadInt16();
                    audioFormat.BitsPerSample         = reader.ReadInt16();

                    if (fmtChunk.ChunkDataSize > 16)
                    {
                        audioFormat.ExtraSize = reader.ReadInt16();

                        if (audioFormat.ExtraSize >= 2)
                        {
                            audioFormat.SamplesPerBlock = reader.ReadInt16();
                        }
                    }

                    // reset position
                    stream.Position = oldPosition;
                    reader          = null;
                }

                var dataChunk = (DataChunk)chunks.FirstOrDefault(x => x is DataChunk);
                if (dataChunk != null)
                {
                    audioFormat.DataChunkSize = dataChunk.ChunkDataSize;
                }
                else
                {
                    throw new ArgumentException("The specified stream does not contain any data chunks.");
                }

                Log.Verbose(audioFormat.ToString());
            }

            // set stream
            _stream = stream;

            // TODO: check with reference implementation
            // https://github.com/xiph/vorbis
            _oggDecoder = new OggDecoder();

            // if the ogg content is embedded in a wave file, copy whole stream into memory
            if (waveFormat != null)
            {
                MemoryStream memoryStream = new MemoryStream();
                stream.CopyTo(memoryStream);
                memoryStream.Position = 0;
                _oggDecoder.Initialize(memoryStream);
                _oggPCMChunkEnumerator = _oggDecoder.GetEnumerator();
            }
            else
            {
                _oggDecoder.Initialize(stream);
                _oggPCMChunkEnumerator = _oggDecoder.GetEnumerator();
            }

            int channels   = _oggDecoder.Channels;
            int sampleRate = _oggDecoder.SampleRate;

            Log.Verbose(string.Format("Ogg Vorbis bitstream is {0} channel, {1} Hz", channels, sampleRate));
            Log.Verbose(string.Format("Comment: {0}", _oggDecoder.Comment));
            Log.Verbose(string.Format("Encoded by: {0}", _oggDecoder.Vendor));

            _waveFormat = new WaveFormat(sampleRate, 16, channels, AudioEncoding.Pcm);

            // store length in bytes according to the new waveformat
            _length = WaveFormat.SecondsToBytes(_oggDecoder.Length);
        }