Пример #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Mp3Stream mp3Stream = new Mp3Stream(AppDomain.CurrentDomain.BaseDirectory + @"/Sample/sample2.mp3");

            WaveFile waveFile       = new WaveFile();
            int      openfileResult = waveFile.OpenFile(AppDomain.CurrentDomain.BaseDirectory + @"/Sample/sample2.wav", WaveFormat.WF_PCM_S16LE, false, 8000, 1);

            if (openfileResult == 0)
            {
                short[,] data = null;
                byte[] buffer = new byte[512];
                int    ret;

                ret = mp3Stream.Read(buffer, 0, buffer.Length);
                Console.WriteLine("File Format: {0}", mp3Stream.Format);
                Console.WriteLine("Frequency: {0}", mp3Stream.Frequency);
                Console.WriteLine("Channel Count: {0}", mp3Stream.ChannelCount);

                if (mp3Stream.ChannelCount <= 0 || mp3Stream.Frequency <= 0)
                {
                    Console.WriteLine("Cannnot decode file.");
                }
                else
                {
                    waveFile.CreateData(ref data, 128);
                    Console.WriteLine("Data Length [{0},{1}]", data.GetLength(0), data.GetLength(1));

                    while (ret != 0)
                    {
                        int i;
                        for (i = 0; i < data.GetLength(1); i++)
                        {
                            if (i * 4 >= ret)
                            {
                                break;
                            }
                            double p1 = (double)BitConverter.ToInt16(buffer, i * 2) / 32767.0;
                            data[0, i] = (short)(
                                ((double)BitConverter.ToInt16(buffer, i * 4) / 32767.0
                                 + (double)BitConverter.ToInt16(buffer, i * 4 + 2) / 32767.0
                                ) * 32767.0 / 2.0);
                        }
                        waveFile.PutData(data, i);
                        ret = mp3Stream.Read(buffer, 0, buffer.Length);
                    }
                }
                waveFile.FlushFile();
                waveFile.CloseFile();
            }
            else
            {
                Console.WriteLine("Can not create waveFile:{0}", openfileResult);
            }

            Console.WriteLine("Finished");
            Console.ReadLine();
            return;
        }
Пример #2
0
 void fillFore()
 {
     if (mp3Stream == null)
     {
         return;
     }
     if (secondaryBuffer == null || secondaryBuffer.Disposed || mp3Stream == null)
     {
         return;
     }
     try
     {
         mp3Stream.Read(buff, 0, halfSize);
         secondaryBuffer.Write(0, new System.IO.MemoryStream(buff), halfSize, LockFlag.None);
     }
     catch { }
 }
Пример #3
0
        private Thread MainThread; //keep track of this, terminate when it closes.

        public MP3Player(string path)
        {
            Stream = new Mp3Stream(path);
            Stream.DecodeFrames(1); //let's get started...

            DecodeNext = new AutoResetEvent(true);
            BufferDone = new AutoResetEvent(false);

            Inst               = new DynamicSoundEffectInstance(Stream.Frequency, AudioChannels.Stereo);
            Inst.IsLooped      = false;
            Inst.BufferNeeded += SubmitBufferAsync;
            SubmitBuffer(null, null);
            SubmitBuffer(null, null);

            NextBuffers   = new List <byte[]>();
            NextSizes     = new List <int>();
            Requests      = 1;
            MainThread    = Thread.CurrentThread;
            DecoderThread = new Thread(() =>
            {
                try
                {
                    while (MainThread.IsAlive)
                    {
                        DecodeNext.WaitOne(128);
                        bool go;
                        lock (this) go = Requests > 0;
                        while (go)
                        {
                            var buf  = new byte[524288];
                            var read = Stream.Read(buf, 0, buf.Length);
                            lock (this)
                            {
                                Requests--;
                                NextBuffers.Add(buf);
                                NextSizes.Add(read);
                                if (read == 0)
                                {
                                    EndOfStream = true;
                                    return;
                                }
                                BufferDone.Set();
                            }
                            lock (this) go = Requests > 0;
                        }
                    }
                }
                catch (Exception e) { }
            });
            DecoderThread.Start();
        }
Пример #4
0
 private void SubmitBuffer(object sender, EventArgs e)
 {
     byte[] buffer = new byte[524288];
     lock (this)
     {
         var read = Stream.Read(buffer, 0, buffer.Length);
         LastChunkSize = read;
         if (read == 0)
         {
             return;
         }
         Inst.SubmitBuffer(buffer, 0, read);
     }
 }
Пример #5
0
 /// <summary>
 /// Callback for the loopback recorder, new audio data is captured.
 /// </summary>
 /// <param name="dataToSendIn">the audio data in wav format</param>
 /// <param name="formatIn">the wav format that's used</param>
 public void OnRecordingDataAvailable(byte[] dataToSendIn, WaveFormat formatIn)
 {
     if (!StreamFormatSelected.Equals(SupportedStreamFormat.Wav))
     {
         if (Mp3Stream == null)
         {
             Mp3Stream = new Mp3Stream(formatIn, StreamFormatSelected);
         }
         Mp3Stream.Encode(dataToSendIn.ToArray());
         dataToSendIn = Mp3Stream.Read();
     }
     if (dataToSendIn.Length > 0)
     {
         devices?.OnRecordingDataAvailable(dataToSendIn, formatIn, reduceLagThreshold, StreamFormatSelected);
     }
 }
Пример #6
0
        public bool FillFromStream(Mp3Stream stream)
        {
            if (stream == null)
                return false;

            int size = stream.Read(byteBuffer, BufferSize);
            bool dataAvailable = size > 0;
            if (dataAvailable)
            {
                XAudioBuffer.AudioDataPointer = GetBufferHandle();
                XAudioBuffer.AudioBytes = size;
                int blockAlign = stream.Channels * 2;
                XAudioBuffer.PlayLength = size / blockAlign;
            }

            return dataAvailable;
        }
Пример #7
0
        void DoLoading(object obj)
        {
            Wavefile  wave   = m_Wavefile;
            Mp3Stream stream = (Mp3Stream)obj;

            BlockArray <Sample> array = wave.m_Samples;

            //SafeStream safeStream = new SafeStream(stream);

            Sample[] sample = new Sample[10000];
            byte[]   buffer = new byte[sample.Length * 4];

            Thread.Sleep(1000);

            while (true)             //safeStream.Position < safeStream.Length)
            {
                //int count;
                //int countMax = (int)Math.Min(1024, (safeStream.Length - safeStream.Position)/4);
                //for (count=0; count <countMax; count ++)
                //{
                //    //sample[count] = new Sample(ReadI2(safeStream), ReadI2(safeStream));
                //    sample[count] = ReadSI2(safeStream);
                //}

                int byteCount = stream.Read(buffer, 0, buffer.Length);
                if (byteCount == 0)
                {
                    break;
                }

                int sampleCount = byteCount / 4;

                for (int i = 0, j = 0; i < sampleCount; i++, j += 4)
                {
                    sample[i] = new Sample((short)(buffer[j] | buffer[j + 1] << 8),
                                           (short)(buffer[j + 2] | buffer[j + 3] << 8));
                }

                array.Write(sample, 0, sampleCount);
                Thread.Sleep(0);
            }

            stream.Dispose();
            wave.FinishedLoading = true;
        }
Пример #8
0
        public void Start()
        {
            Stream = new Mp3Stream(Path);
            Stream.DecodeFrames(1);
            var freq = Stream.Frequency;

            lock (ControlLock)
            {
                if (Disposed)
                {
                    return;
                }
                Inst               = new DynamicSoundEffectInstance(freq, AudioChannels.Stereo);
                Inst.IsLooped      = false;
                Inst.BufferNeeded += SubmitBufferAsync;
                if (_State == SoundState.Playing)
                {
                    Inst.Play();
                }
                else if (_State == SoundState.Paused)
                {
                    Inst.Play();
                    Inst.Pause();
                }
                Inst.Volume = _Volume;
                Inst.Pan    = _Pan;
                Requests    = 2;
            }

            //SubmitBuffer(null, null);
            //SubmitBuffer(null, null);

            DecoderThread = new Thread(() =>
            {
                try
                {
                    while (Active && MainThread.IsAlive)
                    {
                        DecodeNext.WaitOne(128);
                        bool go;
                        lock (this) go = Requests > 0;
                        while (go)
                        {
                            var buf  = new byte[262144];// 524288];
                            var read = Stream.Read(buf, 0, buf.Length);
                            lock (this)
                            {
                                Requests--;
                                NextBuffers.Add(buf);
                                NextSizes.Add(read);
                                if (read == 0)
                                {
                                    EndOfStream = true;
                                    BufferDone.Set();
                                    return;
                                }
                                BufferDone.Set();
                            }
                            lock (this) go = Requests > 0;
                        }
                    }
                }
                catch (Exception e) { }
            });
            DecoderThread.Start();
            DecodeNext.Set();
        }
Пример #9
0
        void Load(System.IO.Stream stream)
        {
            //if (secondaryBuffer == null)
            //{
            //    return;
            //}
            //if (secondaryBuffer.Disposed)
            //{
            //    return;
            //}
            if (Playing)
            {
                secondaryBuffer.Stop();
                Playing = false;
            }
            mp3Stream = new Mp3Stream(stream);

            mp3Stream.Read(buff, 0, 512);
            mp3Stream.Position = 0;

            waveFormat.BitsPerSample         = 16;
            waveFormat.Channels              = mp3Stream.ChannelCount;
            waveFormat.SamplesPerSecond      = mp3Stream.Frequency;
            waveFormat.FormatTag             = WaveFormatTag.Pcm;
            waveFormat.BlockAlign            = (short)(waveFormat.Channels * (waveFormat.BitsPerSample / 8));
            waveFormat.AverageBytesPerSecond = waveFormat.SamplesPerSecond * waveFormat.BlockAlign;

            wholeSize = (int)(waveFormat.AverageBytesPerSecond * TimeSpan.FromSeconds(0.2).TotalSeconds);

            bufferDescription               = new BufferDescription(waveFormat);
            bufferDescription.BufferBytes   = wholeSize;
            bufferDescription.GlobalFocus   = true;
            bufferDescription.ControlVolume = true;

            secondaryBuffer        = new SecondaryBuffer(bufferDescription, game.Devices.DSoundDev);
            secondaryBuffer.Volume = volum;

            #region useless code area
            //autoResetEvent = new System.Threading.AutoResetEvent(false);

            //notify = new Notify(secondaryBuffer);

            //System.Reflection.MethodInfo methodInfo;
            //methodInfo = typeof(SoundManager).GetMethod("fillBack");

            //bufferPositionNotify = new BufferPositionNotify[2];
            //bufferPositionNotify[0] = new BufferPositionNotify();
            //bufferPositionNotify[0].Offset = 0;
            //bufferPositionNotify[0].EventNotifyHandle = this.GetType().GetMethod("fillBack", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).MethodHandle.Value;
            //bufferPositionNotify[1] = new BufferPositionNotify();
            //bufferPositionNotify[1].Offset = halfSize;
            //bufferPositionNotify[1].EventNotifyHandle = this.GetType().GetMethod("fillFore", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).MethodHandle.Value;

            //bufferPositionNotify = new BufferPositionNotify[2];
            //bufferPositionNotify[0] = new BufferPositionNotify();
            //bufferPositionNotify[0].Offset = 0;
            //bufferPositionNotify[0].EventNotifyHandle = autoResetEvent.Handle;
            //bufferPositionNotify[1] = new BufferPositionNotify();
            //bufferPositionNotify[1].Offset = halfSize;
            //bufferPositionNotify[1].EventNotifyHandle = autoResetEvent.Handle;

            //notify.SetNotificationPositions(bufferPositionNotify);
            #endregion
        }