Inheritance: IDisposable
Example #1
0
		private static void LoadOgg(VorbisReader vorbis, out byte[] data, out ALFormat format, out uint sampleRate, out TimeSpan len) {
			sampleRate = (uint)vorbis.SampleRate;
			format = vorbis.Channels == 1 ? ALFormat.Mono16 : ALFormat.Stereo16;
			len = vorbis.TotalTime;

			float[] buffer = new float[vorbis.SampleRate / 10 * vorbis.Channels];
			List<byte> bytes = new List<byte>((int)(vorbis.SampleRate * vorbis.Channels * 2 * len.TotalSeconds));
			int count = 0;
			while ((count = vorbis.ReadSamples(buffer, 0, buffer.Length)) > 0) {
				for (int i = 0; i < count; i++) {
					int temp = (int)(short.MaxValue * buffer [i]);
					if (temp > short.MaxValue) {
						temp = short.MaxValue;
					} else if (temp < short.MinValue) {
						temp = short.MinValue;
					}
					short tempBytes = (short)temp;
					byte byte1 = (byte)((tempBytes >> 8) & 0x00FF);
					byte byte2 = (byte)((tempBytes >> 0) & 0x00FF);

					// Little endian
					bytes.Add(byte2);
					bytes.Add(byte1);
				}
			}
			// TODO: Add better implementation so that there's no need for array copying
			data = bytes.ToArray();
		}
        private static PCMData ReadAll(VorbisReader vorbisStream)
        {
            PCMData pcm;
            pcm.ChannelCount = (short)vorbisStream.Channels;
            pcm.SampleRate = vorbisStream.SampleRate;

            var samples = new List<float>();

            var buffer = new float[DefaultBufferSize];
            int samplesRead = 0;
            while ((samplesRead = vorbisStream.ReadSamples(buffer, 0, buffer.Length)) > 0)
            {
                if (samplesRead != buffer.Length)
                {
                    Array.Resize(ref buffer, samplesRead);
                }
                samples.AddRange(buffer);
                buffer = new float[DefaultBufferSize];
            }

            var samplesArray = samples.ToArray();
            pcm.Data = new byte[samplesArray.Length * SampleSizeBytes];
            Buffer.BlockCopy(samplesArray, 0, pcm.Data, 0, pcm.Data.Length);

            return pcm;
        }
Example #3
0
        /// <summary>
        /// Open a <see cref="Stream"/> of sound for reading.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> to open.</param>
        /// <param name="ownStream">Specify whether the <see cref="SoundReader"/> should close the source <see cref="Stream"/> upon disposing the reader.</param>
        /// <returns>A <see cref="SampleInfo"/> containing sample information.</returns>
        public override SampleInfo Open(Stream stream, bool ownStream = false)
        {
            _reader = new NVorbis.VorbisReader(stream, ownStream);
            _channelCount = _reader.Channels;

            return new SampleInfo((int)(_reader.TotalSamples * _reader.Channels), 
                _reader.Channels, _reader.SampleRate);
        }
Example #4
0
        /// <summary>
        /// Open a <see cref="Stream"/> of sound for reading.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> to open.</param>
        /// <param name="ownStream">Specify whether the <see cref="SoundReader"/> should close the source <see cref="Stream"/> upon disposing the reader.</param>
        /// <returns>A <see cref="SampleInfo"/> containing sample information.</returns>
        public override SampleInfo Open(Stream stream, bool ownStream = false)
        {
            _reader       = new NVorbis.VorbisReader(stream, ownStream);
            _channelCount = _reader.Channels;

            return(new SampleInfo((int)(_reader.TotalSamples * _reader.Channels),
                                  _reader.Channels, _reader.SampleRate));
        }
Example #5
0
 public NVorbisSource(Stream stream)
 {
     if (stream == null)
         throw new ArgumentNullException("stream");
     if(!stream.CanRead)
         throw new ArgumentException("Stream is not readable.", "stream");
     _stream = stream;
     _vorbisReader = new VorbisReader(stream, false);
     _waveFormat = new WaveFormat(_vorbisReader.SampleRate, 32, _vorbisReader.Channels, AudioEncoding.IeeeFloat);
 }
Example #6
0
    public OggSong(string oggFile)
    {
        reader = new VorbisReader(oggFile);
        effect = new DynamicSoundEffectInstance(reader.SampleRate, (AudioChannels)reader.Channels);
        buffer = new byte[effect.GetSampleSizeInBytes(TimeSpan.FromMilliseconds(500))];
        nvBuffer = new float[buffer.Length / 2];

        // when a buffer is needed, set our handle so the helper thread will read in more data
        effect.BufferNeeded += (s, e) => readNextBuffer();
    }
Example #7
0
		public AudioClip (string fileName)
		{
			this.reader = new VorbisReader (fileName);
			this.bufferId = AL.GenBuffer ();
			float[] buffer = new float[this.Samples * this.Channels];
			// ReadSamples could return less data than required for various reasons
			int count = this.reader.ReadSamples (buffer, 0, buffer.Length);
			AL.BufferData (this.bufferId, this.format, buffer, count * sizeof(float), this.SampleRate);
			AudioDevice.CheckError("loading data in OpenAL buffer");
		}
Example #8
0
		private void Dispose(bool manually)
		{
			if (this.disposed) return;
			
			if (this.ovStream != null)
			{
				this.ovStream.Dispose();
				this.ovStream = null;
			}

			this.disposed = true;
		}
Example #9
0
 public NVorbisDecoder(Stream stream)
 {
     //reset the stream
     stream.Seek (0, SeekOrigin.Begin);
     reader = new VorbisReader (stream, false);
     if (reader.Channels == 1) {
         format = ALFormat.Mono16;
     } else if (reader.Channels == 2) {
         format = ALFormat.Stereo16;
     } else {
         throw new NotSupportedException (string.Format ("{0} channels not supported", reader.Channels));
     }
 }
        public static void SaveVorbisDataToWAV(byte[] vorbisData, string filePath)
        {
            using (var outStream = new BinaryWriter(new FileStream(filePath, FileMode.Create)))
            {
                using (var vorbisStream = new VorbisReader(new MemoryStream(vorbisData), true))
                {
                    var pcm = ReadAll(vorbisStream);

                    WriteRIFFFileHeaderChunk(outStream, pcm);
                    WriteRIFFFormatChunk(outStream, pcm);
                    WriteRIFFDataChunk(outStream, pcm);
                }
            }
        }
Example #11
0
 private SoundEffect LoadOgg(Stream stream)
 {
     using (var reader = new VorbisReader(stream, false))
     {
         float[] _buffer = new float[reader.TotalSamples];
         byte[] buffer = new byte[reader.TotalSamples * 2];
         reader.ReadSamples(_buffer, 0, _buffer.Length);
         for (int i = 0; i < _buffer.Length; i++)
         {
             short val = (short)Math.Max(Math.Min(short.MaxValue * _buffer[i], short.MaxValue), short.MinValue);
             var decoded = BitConverter.GetBytes(val);
             buffer[i * 2] = decoded[0];
             buffer[i * 2 + 1] = decoded[1];
         }
         return new SoundEffect(buffer, reader.SampleRate, reader.Channels == 1 ? AudioChannels.Mono : AudioChannels.Stereo);
     }
 }
Example #12
0
        public OggAudioSource(Stream file, bool streaming = true)
        {
            Streaming = streaming;
            _fileStream = file;

            _reader = new VorbisReader(file, false);
            _sampleRate = _reader.SampleRate;
            _format = (_reader.Channels == 2 ? ALFormat.Stereo16 : ALFormat.Mono16);

            if(!Streaming)
            {
                _data = new short[_reader.TotalSamples];
                float[] samples = new float[_reader.TotalSamples];
                _reader.ReadSamples(samples, 0, (int)_reader.TotalSamples);
                CastSamples(ref samples, ref _data, samples.Length);
            }
        }
Example #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OggReader"/> class.
 /// </summary>
 public OggReader()
 {
     _reader       = null;
     _channelCount = 0;
 }
Example #14
0
		public OggMusicStream(Stream stream)
		{
			baseStream = stream;
			reader = new VorbisReader(stream, false);
		}
Example #15
0
 public override void Reset()
 {
     _fileStream.Position = 0;
     _reader = new VorbisReader(_fileStream, false);
 }
Example #16
0
        internal void Open(bool precache = false)
        {
            Reader = new VorbisReader(oggFileName);

            if (precache)
            {
                // Fill first buffer synchronously
                OggStreamer.Instance.FillBuffer(this, alBufferIds[0]);
                AL.SourceQueueBuffer(alSourceId, alBufferIds[0]);
                ALHelper.CheckError("Failed to queue buffer.");
            }

            Ready = true;
        }
Example #17
0
		internal VorbisStreamHandle(string fileName)
		{
			this.ovStream = new VorbisReader(fileName);
		}
Example #18
0
 public OggFile( Stream stream )
     : base()
 {
     _reader = new VorbisReader( stream, true );
 }
Example #19
0
 VorbisAudioStream(VorbisReader reader)
 {
     if (reader == null)
         throw new ArgumentNullException("reader");
     this.reader = reader;
 }
Example #20
0
		public static void LoadOgg(Stream file, out byte[] data, out ALFormat format, out uint sampleRate, out TimeSpan len) {
			using (VorbisReader vorbis = new VorbisReader(file, false)) {
				LoadOgg(vorbis, out data, out format, out sampleRate, out len);
			}
		}
Example #21
0
    public NVOggPlayer(System.IO.Stream s)
    {
        reader = new NVorbis.VorbisReader(s, true);

        isPlaying = true;
    }
Example #22
0
    public NVOggPlayer(System.IO.Stream s)
    {
        reader = new NVorbis.VorbisReader(s, true);

        isPlaying = true;
    }
Example #23
0
		public static uint BufferFromOgg(Stream file) {
			using (VorbisReader vorbis = new VorbisReader(file, false)) {
				return BufferFromOgg(vorbis);
			}
		}
Example #24
0
		public static uint BufferFromOgg(string file) {
			using (VorbisReader vorbis = new VorbisReader(file)) {
				return BufferFromOgg(vorbis);
			}
		}
Example #25
0
    void loadData()
    {
        if (filepath != string.Empty && File.Exists(filepath))
        {
#if BASS_AUDIO
            long        trackLengthInBytes = Bass.BASS_ChannelGetLength(handle);
            const float FRAME_TIME         = 0.002f;
            long        frameLengthInBytes = Bass.BASS_ChannelSeconds2Bytes(handle, FRAME_TIME);
            int         NumFrames          = (int)System.Math.Round(1f * trackLengthInBytes / frameLengthInBytes);

            _data = new float[NumFrames * 2];

            float[] levels = new float[2];
            for (int i = 0; i < _data.Length && !stop; i += 2)
            {
                Bass.BASS_ChannelGetLevel(handle, levels, FRAME_TIME, BASSLevel.BASS_LEVEL_STEREO);
                float average = (levels[0] + levels[1]) / 2.0f;
                _data[i]     = -average;
                _data[i + 1] = average;
            }
#else
            byte[]  bytes      = File.ReadAllBytes(filepath);
            float[] sampleData = new float[0];
            switch (Path.GetExtension(filepath))
            {
            case (".ogg"):
                NVorbis.VorbisReader vorbis = new NVorbis.VorbisReader(filepath);
                vorbis.ClipSamples = false;

                _data = new float[vorbis.TotalSamples * vorbis.Channels];

                //vorbis.ReadSamples(_data, 0, _data.Length);

                int count = 0;
                while ((count += vorbis.ReadSamples(_data, count, 16000)) > 0 && !stop)
                {
                }

                break;

            case (".wav"):
                WAV wav = new WAV(bytes);
                sampleData = NAudioPlayer.InterleaveChannels(wav);
                break;

            case (".mp3"):
                NAudioPlayer.WAVFromMp3Data(bytes, out sampleData);
                break;

            default:
                return;
            }
#endif
            if (!stop)
            {
#if !BASS_AUDIO
                _data = sampleData;
#endif

                Debug.Log("Sample length: " + _data.Length);
            }
            else
            {
                _data = new float[0];
            }
        }
    }
Example #26
0
        internal void Open(bool precache = false)
        {
            underlyingStream.Seek(0, SeekOrigin.Begin);
            Reader = new VorbisReader(underlyingStream, false);

            if (precache)
            {
                // Fill first buffer synchronously
                OggStreamer.Instance.FillBuffer(this, alBufferIds[0]);
                AL.SourceQueueBuffer(alSourceId, alBufferIds[0]);
                ALHelper.Check();

                // Schedule the others asynchronously
                OggStreamer.Instance.AddStream(this);
            }

            Ready = true;
        }
Example #27
0
		public void Rewind()
		{
			baseStream.Position = 0;
			reader = new VorbisReader(baseStream, false);
		}
Example #28
0
 /// <summary>
 /// Initialize a new instance of <see cref="VorbisAudioSource"/> class with specified file path.
 /// </summary>
 public VorbisAudioSource(string path)
 {
     reader = new NVorbis.VorbisReader(path);
 }
Example #29
0
 internal void OpenReader()
 {
     lastStreamPosition = 0;
     CurrentClip.underlyingStream.Seek(lastStreamPosition, SeekOrigin.Begin);
     Reader = new VorbisReader(CurrentClip.underlyingStream, false);
 }
Example #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OggReader"/> class.
 /// </summary>
 public OggReader()
 {
     _reader       = null;
     _channelCount = 0;
 }
Example #31
0
		private void Streamer (object arg)
		{
			string fileName = (string)arg;

			VorbisReader vreader = new VorbisReader (fileName);

			// 3 seconds buffering
			int bufLen = vreader.Channels * vreader.SampleRate * 3;
			float[] buffer = new float[bufLen];

			if (this.bufferIds == null) {
				this.bufferIds = AL.GenBuffers (3);
				AudioDevice.CheckError ("allocating OpenAL buffers for streaming");
			}

			ALFormat format = vreader.Channels == 2 ? ALFormat.StereoFloat32Ext : ALFormat.MonoFloat32Ext;

			// buffer data
			int i;
			for (i = 0; i < bufferIds.Length; i++) {
				int count = vreader.ReadSamples (buffer, 0, bufLen);
				// end of the stream ?
				if (count == 0) {
					if (!this.streamLooping)
						break;
					vreader.DecodedPosition = 0;
					count = vreader.ReadSamples (buffer, 0, bufLen);
				}
				AL.BufferData<float> (this.bufferIds [i], format, buffer, count * sizeof(float), vreader.SampleRate);
				AudioDevice.CheckError ("loading data in OpenAL buffer for streaming");
			}
			AL.SourceQueueBuffers (this.audioSourceId, i, bufferIds);

			AL.SourcePlay (this.audioSourceId);

			while (true) {
				Thread.Sleep (30);
				int processed = 0;
				AL.GetSource (this.audioSourceId, ALGetSourcei.BuffersProcessed, out processed);
				while (processed > 0) {
					int bufferId = AL.SourceUnqueueBuffer (this.audioSourceId);
					int count = vreader.ReadSamples (buffer, 0, bufLen);
					// end of the straem ?
					if (count == 0) {
						if (!this.streamLooping) {
							this.Stop ();
							// to reset status
							AL.Source (this.audioSourceId, ALSourcei.Buffer, 0);
							return;
						}
						vreader.DecodedPosition = 0;
						count = vreader.ReadSamples (buffer, 0, bufLen);
					}
					AL.BufferData<float> (bufferId, format, buffer, count * sizeof(float), vreader.SampleRate);
					AudioDevice.CheckError ("loading data in OpenAL buffer for streaming");
					AL.SourceQueueBuffer (this.audioSourceId, bufferId);
					processed--;
				}
			}
		}
Example #32
0
		internal VorbisStreamHandle(byte[] memory)
		{
			this.ovStream = new VorbisReader(new MemoryStream(memory), true);
		}
Example #33
0
		public ISoundData Decode(Stream stream)
		{
			VorbisReader reader = null;
			try
			{
				reader = new VorbisReader (stream, false);

				int channels = reader.Channels;
				const int BITS_PER_SAMPLE = 16;
				int sampleRate = reader.SampleRate;

				//Code from: https://github.com/AdamsLair/duality/blob/a911c46b6bc830c05d3bb1202f8e7060543eaefa/Duality/Audio/OggVorbis.cs
				List<float[]> allBuffers = new List<float[]>();
				bool eof = false;
				int totalSamplesRead = 0;
				int dataRead = 0;
				while (!eof)
				{
					float[] buffer = new float[DEFAULT_BUFFER_SIZE];
					int bufferSamplesRead = 0;
					while(bufferSamplesRead < buffer.Length)
					{
						int samplesRead;
						lock (_readMutex)
						{
							samplesRead = reader.ReadSamples(buffer, dataRead, buffer.Length - dataRead);
						}
						if (samplesRead > 0)
						{
							bufferSamplesRead += samplesRead;
						}
						else
						{
							eof = true;
							break;
						}
					}
					allBuffers.Add(buffer);
					totalSamplesRead += bufferSamplesRead;
				}

				if (totalSamplesRead > 0)
				{
					short[] data = new short[totalSamplesRead];
					int offset = 0;
					for (int i = 0; i < allBuffers.Count; i++)
					{
						int len = Math.Min(totalSamplesRead - offset, allBuffers[i].Length);
						castBuffer(allBuffers[i], data, offset, len);
						offset += len;
					}
					return new SoundData(channels, BITS_PER_SAMPLE, sampleRate, data, Marshal.SizeOf(typeof(short)) * data.Length);
				}
				else
				{
					Debug.WriteLine("OggDecoder: No samples found in ogg file");
					return null;
				}
			}
			catch (InvalidDataException e)
			{
				Debug.WriteLine("OggDecoder: Failed to read ogg. " + e.ToString());
				return null;
			}
			finally
			{
				if (reader != null) reader.Dispose();
			}
		}
Example #34
0
		private unsafe static uint BufferFromOgg(VorbisReader vorbis) {
			uint result;
			AL.GenBuffers(1, out result);

			byte[] data;
			ALFormat format;
			uint sampleRate;
			TimeSpan len;
			LoadOgg(vorbis, out data, out format, out sampleRate, out len);

			fixed (byte * dataPtr = &data[0]) {
				IntPtr dataIntPtr = new IntPtr(dataPtr);
				AL.BufferData(result, format, dataIntPtr, data.Length, (int)sampleRate);
			}

			return result;
		}
Example #35
0
 internal void Close()
 {
     if (Reader != null)
     {
         Reader.Dispose();
         Reader = null;
     }
     Ready = false;
 }