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();
            }
        }
Beispiel #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;
        }
Beispiel #3
0
 private static byte[] get_ogg_pcm_data(NVorbis.VorbisReader vorbis)
 {
     return(vorbis.SelectMany(x => x).ToArray());
 }
Beispiel #4
0
        private static void sound_effect_from_ogg(out SoundEffect sound, string cue_name, out int intro_start, out int loop_start, out int loop_length)
        {
            if (!LOOP_DATA.ContainsKey(cue_name))
            {
                try
                {
                    using (Stream cue_stream = TitleContainer.OpenStream(cue_name))
                    {
#if __ANDROID__
                        MemoryStream stream = new MemoryStream();
                        cue_stream.CopyTo(stream);
                        using (var vorbis = new NVorbis.VorbisReader(stream, cue_name, false))
#else
                        using (var vorbis = new NVorbis.VorbisReader(cue_stream, cue_name, false))
#endif
                        {
                            // Stores sound effect data, so it doesn't have to be reloaded repeatedly
                            if (!SOUND_DATA.ContainsKey(cue_name))
                            {
                                SOUND_DATA[cue_name] = get_ogg_pcm_data(vorbis);
                            }

                            get_loop_data(vorbis, out intro_start, out loop_start, out loop_length);

                            LOOP_DATA[cue_name]    = new int[5];
                            LOOP_DATA[cue_name][0] = intro_start;
                            LOOP_DATA[cue_name][1] = loop_start;
                            LOOP_DATA[cue_name][2] = loop_length;
                            LOOP_DATA[cue_name][3] = vorbis.Channels;
                            LOOP_DATA[cue_name][4] = vorbis.SampleRate;
                        }
#if __ANDROID__
                        stream.Dispose();
#endif
                    }
                }
                catch (FileNotFoundException ex)
                {
                    throw;
                }
#if __ANDROID__
                catch (Java.IO.FileNotFoundException e)
                {
                    throw;
                }
#endif
            }

            intro_start = LOOP_DATA[cue_name][0];
            loop_start  = LOOP_DATA[cue_name][1];
            loop_length = LOOP_DATA[cue_name][2];
            using (MemoryStream stream = new MemoryStream())
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    // Writes the decoded ogg data to a memorystream
                    WriteWave(writer, LOOP_DATA[cue_name][3], LOOP_DATA[cue_name][4], SOUND_DATA[cue_name]);
                    // Resets the stream's position back to 0 after writing
                    stream.Position = 0;
#if __ANDROID__
                    sound = SoundEffect.FromStream(
                        stream, intro_start, loop_start, loop_start + loop_length);
#else
                    sound = SoundEffect.FromStream(stream);
#endif
                    sound.Name = cue_name;
                }
        }
Beispiel #5
0
        public VorbisWaveReader(System.IO.Stream sourceStream)
        {
            _reader = new NVorbis.VorbisReader(sourceStream, false);

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

            _waveFormat = NAudio.Wave.WaveFormat.CreateIeeeFloatWaveFormat(_reader.SampleRate, _reader.Channels);
        }
Beispiel #7
0
        private static void DownloadSongs()
        {
            Settings.Instance.Server.Downloaded.GetDirectories().AsParallel().ForAll(dir => dir.Delete(true));

            Settings.Instance.AvailableSongs.Songs.AsParallel().ForAll(id => {
                var zipPath = Path.Combine(Settings.Instance.Server.Downloads.FullName, $"{id}.zip");
                Thread.Sleep(25);
                using (var client = new WebClient()) {
                    client.Headers.Add("user-agent",
                                       $"BeatSaverMultiplayerServer-{Assembly.GetEntryAssembly().GetName().Version}");
                    if (Settings.Instance.Server.Downloads.GetFiles().All(o => o.Name != $"{id}.zip"))
                    {
                        Logger.Instance.Log($"Downloading {id}.zip");
                        client.DownloadFile($"https://beatsaver.com/dl.php?id={id}", zipPath);
                    }
                }

                ZipArchive zip = null;
                try {
                    zip = ZipFile.OpenRead(zipPath);
                }
                catch (Exception ex) {
                    Logger.Instance.Exception(ex.Message);
                }

                var songName = zip?.Entries[0].FullName.Split('/')[0];
                try {
                    zip?.ExtractToDirectory(Settings.Instance.Server.Downloaded.FullName);
                    try {
                        zip?.Dispose();
                    }
                    catch (IOException ex) {
                        Logger.Instance.Exception($"Failed to remove Zip [{id}]");
                    }
                }
                catch (IOException ex) {
                    Logger.Instance.Exception($"Folder [{songName}] exists. Continuing.");
                    try {
                        zip?.Dispose();
                    }
                    catch (IOException) {
                        Logger.Instance.Exception($"Failed to remove Zip [{id}]");
                    }
                }
            });

            Logger.Instance.Log("All songs downloaded!");

            List <CustomSongInfo> _songs = SongLoader.RetrieveAllSongs();

            _songs.AsParallel().ForAll(song => {
                Logger.Instance.Log($"Processing {song.songName} {song.songSubName}");
                using (NVorbis.VorbisReader vorbis =
                           new NVorbis.VorbisReader($"{song.path}/{song.difficultyLevels[0].audioPath}")) {
                    song.duration = vorbis.TotalTime;
                }

                availableSongs.Add(song);
            });

            Logger.Instance.Log("Done!");
        }
 /// <summary>
 /// Open a <see cref="Stream"/> of sound for reading.
 /// </summary>
 /// <param name="stream"><see cref="Stream"/> to open.</param>
 /// <param name="leaveOpen">Specifies whether the <paramref name="stream"/> should leave open after the current instance of the <see cref="SoundReader"/> disposed.</param>
 /// <returns>A <see cref="SampleInfo"/> containing sample information if decoder is can handle the stream, otherwise <c>null</c>.</returns>
 /// <inheritdoc/>
 protected internal override SampleInfo Initialize(Stream stream, bool leaveOpen = false)
 {
     reader = new NVorbis.VorbisReader(stream, leaveOpen);
     return(new SampleInfo(reader.TotalSamples * reader.Channels, reader.Channels, reader.SampleRate));
 }
Beispiel #9
0
        private static void DownloadSongs()
        {
            if (!Directory.Exists("AvailableSongs"))
            {
                Directory.CreateDirectory("AvailableSongs");
            }

            using (var client = new WebClient())
            {
                client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                                               "(compatible; MSIE 6.0; Windows NT 5.1; " +
                                               ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                foreach (string dir in Directory.GetDirectories("AvailableSongs/"))
                {
                    Directory.Delete(dir, true);
                }

                foreach (int id in availableSongsIDs)
                {
                    if (!File.Exists("AvailableSongs/" + id + ".zip"))
                    {
                        Console.WriteLine("Downloading " + id + ".zip");
                        client.DownloadFile("https://beatsaver.com/dl.php?id=" + id, "AvailableSongs/" + id + ".zip");

                        FastZip zip = new FastZip();
                        Console.WriteLine("Extracting " + id + ".zip...");
                        zip.ExtractZip("AvailableSongs/" + id + ".zip", "AvailableSongs", null);
                    }
                    else
                    {
                        string downloadedSongPath = "";

                        using (var zf = new ZipFile("AvailableSongs/" + id + ".zip"))
                        {
                            foreach (ZipEntry ze in zf)
                            {
                                if (ze.IsFile)
                                {
                                    if (string.IsNullOrEmpty(downloadedSongPath) && ze.Name.IndexOf('/') != -1)
                                    {
                                        downloadedSongPath = "AvailableSongs/" + ze.Name.Substring(0, ze.Name.IndexOf('/'));
                                    }
                                }
                                else if (ze.IsDirectory)
                                {
                                    downloadedSongPath = "AvailableSongs/" + ze.Name;
                                }
                            }
                        }

                        if (downloadedSongPath.Contains("/autosaves"))
                        {
                            downloadedSongPath = downloadedSongPath.Replace("/autosaves", "");
                        }

                        if (!Directory.Exists(downloadedSongPath))
                        {
                            FastZip zip = new FastZip();
                            Console.WriteLine("Extracting " + id + ".zip...");
                            zip.ExtractZip("AvailableSongs/" + id + ".zip", "AvailableSongs", null);
                        }
                    }
                }

                Console.WriteLine("All songs downloaded!");

                List <CustomSongInfo> _songs = SongLoader.RetrieveAllSongs();

                foreach (CustomSongInfo song in _songs)
                {
                    Console.WriteLine("Processing " + song.songName + " " + song.songSubName);
                    using (NVorbis.VorbisReader vorbis = new NVorbis.VorbisReader(song.path + "/" + song.difficultyLevels[0].audioPath))
                    {
                        song.duration = vorbis.TotalTime;
                    }

                    availableSongs.Add(song);
                }

                Console.WriteLine("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);
            }
        }
Beispiel #11
0
        public VorbisWaveReader(System.IO.Stream sourceStream)
        {
            _reader = new NVorbis.VorbisReader(sourceStream, false);

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

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

            base.Dispose(disposing);
        }
Beispiel #14
0
 private static void get_loop_data(NVorbis.VorbisReader reader, out int intro_start, out int loop_start, out int loop_length)
 {
     string[] comments = reader.Comments;
     get_loop_data(comments, out intro_start, out loop_start, out loop_length);
 }
        /**
         * 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.");
        }
Beispiel #16
0
        private static SoundEffectInstance get_music(string cue_name)
        {
            SoundEffect         song = null;
            SoundEffectInstance music = null;
            int intro_start = 0, loop_start = -1, loop_length = -1;

            NVorbis.VorbisReader vorbis = null;
            try
            {
                try
                {
                    Stream cue_stream = TitleContainer.OpenStream(@"Content\Audio\BGM\" + cue_name + ".ogg");


#if __ANDROID__
                    MemoryStream stream = new MemoryStream();
                    cue_stream.CopyTo(stream);
                    vorbis = new NVorbis.VorbisReader(stream, cue_name, true);
#else
                    vorbis = new NVorbis.VorbisReader(cue_stream, cue_name, true);
#endif
                    get_loop_data(vorbis, out intro_start, out loop_start, out loop_length);


                    // If the loop points are set past the end of the song, don't play
                    if (vorbis.TotalSamples < loop_start || vorbis.TotalSamples < loop_start + loop_length)
                    {
#if DEBUG
                        throw new IndexOutOfRangeException("Loop points are set past the end of the song");
#endif
#if __ANDROID__
                        cue_stream.Dispose();
                        vorbis.Dispose();
#else
                        vorbis.Dispose();
#endif
                        throw new FileNotFoundException();
                    }
#if __ANDROID__
                    cue_stream.Dispose();
#endif
                }
                catch (FileNotFoundException ex)
                {
                    throw;
                }
#if __ANDROID__
                catch (Java.IO.FileNotFoundException e)
                {
                    throw;
                }
#endif
            }
            // If loaded as an ogg failed, try loading as a SoundEffect
            catch (FileNotFoundException ex)
            {
                intro_start = 0;
                loop_start  = -1;
                loop_length = -1;
                song        = Global.Content.Load <SoundEffect>(@"Audio/" + cue_name);
            }

            // If the file is an ogg file and was found and initialized successfully
            if (vorbis != null)
            {
                music = get_vorbis_music(vorbis, cue_name,
                                         intro_start, loop_start, loop_length);
            }
            else
            {
                music = get_effect_music(song, cue_name, intro_start, loop_start, loop_length);
            }

            if (music != null)
            {
                music.IsLooped = true;
            }
#if !__ANDROID__
            if (song != null)
            {
                song.Dispose();
            }
#endif
            return(music);
        }
Beispiel #17
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;
 }