Exemple #1
0
        private static void Main(string[] args)
        {
            string fileName;
            if (args.Length == 1)
            {
                fileName = args[0];
            }
            else
            {
                var dialog = new OpenFileDialog {Title = "Select an audio file (wma, mp3, ...etc.) or video file..."};
                if (dialog.ShowDialog() != DialogResult.OK)
                    return;
                fileName = dialog.FileName;
            }

            var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var audioDecoder = new AudioDecoder(stream);

            var outputWavStream = new FileStream("output.wav", FileMode.Create, FileAccess.Write);

            var wavWriter = new WavWriter(outputWavStream);

            // Write the WAV file
            wavWriter.Begin(audioDecoder.WaveFormat);

            // Decode the samples from the input file and output PCM raw data to the WAV stream.
            wavWriter.AppendData(audioDecoder.GetSamples());

            // Close the wav writer.
            wavWriter.End();

            audioDecoder.Dispose();
            outputWavStream.Close();
            stream.Close();
        }
Exemple #2
0
 public static void Destroy()
 {
     if (Music.m_XAudio2 == null)
     {
         return;
     }
     Music.Stop();
     if (Music.m_SourceVoice != null)
     {
         Music.m_SourceVoice.Stop();
         ((Voice)Music.m_SourceVoice).DestroyVoice();
         Music.m_SourceVoice = (SourceVoice)null;
     }
     if (Music.m_AudioDecoder != null)
     {
         (Music.m_AudioDecoder).Dispose();
         Music.m_AudioDecoder = (AudioDecoder)null;
     }
     ((Voice)Music.m_MasteringVoice).DestroyVoice();
     ((DisposeBase)Music.m_MasteringVoice).Dispose();
     Music.m_MasteringVoice = (MasteringVoice)null;
     ((DisposeBase)Music.m_XAudio2).Dispose();
     Music.m_XAudio2 = (SharpDX.XAudio2.XAudio2)null;
     MediaFactory.Shutdown();
     Music.IsDisposed = true;
     Music.m_PlayingTask.Wait();
 }
Exemple #3
0
    void Start()
    {
        print("before audio decoder ctor");
        AudioDecoder audioDecoder = new AudioDecoder(KH_SAMPLE_RATE, KH_CHANNEL_COUNT);

        print("after audio decoder ctor");
    }
Exemple #4
0
        public Stream EncodeAsOggOpus(Stream audioStream)
        {
            var oggStream = new MemoryStream();

            logger.LogInformation("Transcoding audio stream to ogg");
            logger.LogDebug($"Transcoding with {config.Music.EncodingSampleRate} samples and {config.Music.EncodingBitrate} bits per second");
            try
            {
                using (var inputStream = new AVIOStream(audioStream, FileAccess.Read))
                    using (var inputCtx = new InputContext(inputStream))
                        using (var decoder = new AudioDecoder(inputCtx))
                            using (var outputStream = new AVIOStream(oggStream, FileAccess.Write))
                                using (var outputCtx = new OutputContext(outputStream))
                                {
                                    outputCtx.GuessOutputFormat(null, ".ogg", null);
                                    using (var encoder = new AudioEncoder(outputCtx, FFmpeg.AutoGen.AVCodecID.AV_CODEC_ID_OPUS, config.Music.EncodingSampleRate, 2, config.Music.EncodingBitrate))
                                        using (var transcoder = new AudioTranscoder(encoder, decoder))
                                        {
                                            outputCtx.WriteFileHeader();
                                            transcoder.Transcode(true);
                                            outputCtx.WriteFileTrailer();
                                            logger.LogDebug("Transcoding finished");
                                        }
                                }
                oggStream.Position = 0;
                return(oggStream);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Exception while transcoding audio stream");
                oggStream.Dispose();
                return(null);
            }
        }
Exemple #5
0
        public SoundStreamedDataSource(FileInfo fi)
        {
            //To avoid Disk activity, preload the sound file into memoryStream
            using (FileStream fileStream = File.OpenRead(fi.FullName))
            {
                _bufferedCompressedFile = new MemoryStream();
                _bufferedCompressedFile.SetLength(fileStream.Length);
                fileStream.Read(_bufferedCompressedFile.GetBuffer(), 0, (int)fileStream.Length);
            }

            //Pre allocate buffers
            _audioBuffersRing = new AudioBuffer[bufferRing];
            _memBuffers       = new DataPointer[bufferRing];
            for (int i = 0; i < bufferRing; i++)
            {
                _audioBuffersRing[i]   = new AudioBuffer();
                _memBuffers[i].Size    = 32 * 1024; // default size 32Kb
                _memBuffers[i].Pointer = Utilities.AllocateMemory(_memBuffers[i].Size);
            }

            Volume = 1;
            //Get File metaData
            _audioDecoder = new AudioDecoder(_bufferedCompressedFile);
            WaveFormat    = _audioDecoder.WaveFormat;

            _sleep = new AutoResetEvent(false);
        }
Exemple #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AudioPlayer" /> class.
        /// </summary>
        /// <param name="xaudio2">The xaudio2 engine.</param>
        /// <param name="audioStream">The input audio stream.</param>
        public AudioPlayer(string file)
        {
            this.xaudio2 = new XAudio2();
            audioDecoder = new AudioDecoder(SoundsManager.getAudioStream(file));
            var test = SoundsManager.getAudio(file);

            sourceVoice = new SourceVoice(test.Item4, test.Item1, true);
            localVolume = 1.0f;

            sourceVoice.BufferEnd += sourceVoice_BufferEnd;
            sourceVoice.Start();

            bufferEndEvent      = new AutoResetEvent(false);
            playEvent           = new ManualResetEvent(false);
            waitForPlayToOutput = new ManualResetEvent(false);

            clock = new Stopwatch();

            // Pre-allocate buffers
            audioBuffersRing = new AudioBuffer[3];
            memBuffers       = new DataPointer[audioBuffersRing.Length];
            for (int i = 0; i < audioBuffersRing.Length; i++)
            {
                audioBuffersRing[i]   = new AudioBuffer();
                memBuffers[i].Size    = 32 * 1024; // default size 32Kb
                memBuffers[i].Pointer = Utilities.AllocateMemory(memBuffers[i].Size);
            }

            // Initialize to stopped
            State = AudioPlayerState.Stopped;

            // Starts the playing thread
            playingTask = Task.Factory.StartNew(PlayAsync, TaskCreationOptions.LongRunning);
        }
Exemple #7
0
        private void Osu_Signal(string line)
        {
            var data = line.Split('|');

            if (data.Length != 5)
            {
                return;
            }
            // [ time, audioPath, audioCurrentTime, audioPlaybackRate, beatmapPath ]
            // 재생 중인 곡이 바꼈다!
            if (data[1] != curAudio.Path)
            {
                using (var fs = new FileStream(data[1], FileMode.Open, FileAccess.Read))
                {
                    curAudio = AudioDecoder.GetDecoder(fs)?.Decode(fs);
                }
                curAudio.Path = data[1];
                using (var sr = new StreamReader(data[4]))
                {
                    curAudio.Beatmap = BeatmapDecoder.GetDecoder(sr)?.Decode(sr);
                }
                UpdateLyrics();
            }
            curTime = DateTimeOffset.Now.Subtract(
                DateTimeOffset.FromFileTime(Convert.ToInt64(data[0], 16))
                ).TotalSeconds + Convert.ToDouble(data[2]);
            _playbackRate = 1 + Convert.ToDouble(data[3]) / 100;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AudioPlayer" /> class.
        /// </summary>
        /// <param name="xaudio2">The xaudio2 engine.</param>
        /// <param name="audioStream">The input audio stream.</param>
        public AudioPlayer(XAudio2 xaudio2, Stream audioStream)
        {
            this.xaudio2 = xaudio2;
            audioDecoder = new AudioDecoder(audioStream);
            sourceVoice  = new SourceVoice(xaudio2, audioDecoder.WaveFormat);
            localVolume  = 1.0f;
            crossfade    = TimeSpan.FromSeconds(10);

            sourceVoice.BufferEnd += sourceVoice_BufferEnd;
            sourceVoice.Start();

            bufferEndEvent      = new AutoResetEvent(false);
            playEvent           = new ManualResetEvent(false);
            waitForPlayToOutput = new ManualResetEvent(false);

            clock = new Stopwatch();

            // Pre-allocate buffers
            audioBuffersRing = new AudioBuffer[3];
            memBuffers       = new DataPointer[audioBuffersRing.Length];
            for (int i = 0; i < audioBuffersRing.Length; i++)
            {
                audioBuffersRing[i]   = new AudioBuffer();
                memBuffers[i].Size    = 32 * 1024; // default size 32Kb
                memBuffers[i].Pointer = Utilities.AllocateMemory(memBuffers[i].Size);
            }

            // Initialize to stopped
            State = AudioPlayerState.Stopped;

            // Starts the playing thread
            playingTask = Task.Factory.StartNew(PlayAsync, TaskCreationOptions.LongRunning);
        }
        private void DisposePlayer()
        {
            audioDecoder.Dispose();
            audioDecoder = null;

            sourceVoice.Dispose();
            sourceVoice = null;

            for (int i = 0; i < audioBuffersRing.Length; i++)
            {
                Utilities.FreeMemory(memBuffers[i].Pointer);
                memBuffers[i].Pointer = IntPtr.Zero;
            }
        }
Exemple #10
0
        /// <summary>
        /// dis pose the woto player, and realese all the resources.
        /// </summary>
        /// <param name="force">
        /// the value to check if you want to lose all the
        /// resources or not.
        /// </param>
        private void DisposePlayer(bool force = false)
        {
            try
            {
                if (!(audioDecoder is null))
                {
                    audioDecoder.Dispose();
                    if (force)
                    {
                        audioDecoder = null;
                    }
                }
                if (!(masteringVoice is null))
                {
                    masteringVoice.Dispose();
                    if (force)
                    {
                        sourceVoice = null;
                    }
                }
                if (!(sourceVoice is null))
                {
                    sourceVoice.Dispose();
                    if (force)
                    {
                        sourceVoice = null;
                    }
                }
                if (!(_stream is null))
                {
                    _stream.Close();
                    _stream.Dispose();
                    _stream = null;
                }

                if (!(audioBuffersRing is null || memBuffers is null))
                {
                    for (int i = 0; i < audioBuffersRing.Length; i++)
                    {
                        Utilities.FreeMemory(memBuffers[i].Pointer);
                        memBuffers[i].Pointer = IntPtr.Zero;
                    }
                }
            }
            catch
            {
                return;
            }
        }
Exemple #11
0
        public void Register(string filepath)
        {
            CheckSupported();
            if (sounds.ContainsKey(filepath))
            {
                return;
            }
            var nfs     = new NativeFileStream(filepath, NativeFileMode.Open, NativeFileAccess.Read);
            var decoder = new AudioDecoder(nfs);

            lock (sounds) sounds.Add(filepath, decoder);

            var freelist = new Queue <SourceVoice>();

            voices.Add(decoder, freelist);
        }
Exemple #12
0
    void Start()
    {
        IPAddress address = IPAddress.Parse("127.0.0.1");
        int       port    = 7777;

        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
        {
            ReceiveBufferSize = 1024 * 1024
        };

        ringBuffer       = new RingBuffer((int)(KH_LATENCY_SECONDS * 2 * KH_BYTES_PER_SECOND / sizeof(float)));
        udpSocket        = new UdpSocket(socket, new IPEndPoint(address, port));
        audioDecoder     = new AudioDecoder(KH_SAMPLE_RATE, KH_CHANNEL_COUNT);
        lastAudioFrameId = -1;

        udpSocket.Send(PacketHelper.createPingReceiverPacketBytes());
    }
        public override void OnStart(EncoderOption option)
        {
            this.option = option;

            var audio_file = StoryboardInstanceManager.ActivityInstance?.Info?.audio_file_path;

            audio_reader = new MediaReader(audio_file);

            audio_decoder = audio_reader.Decoders.OfType <AudioDecoder>().FirstOrDefault();

            #region Video Init

            var video_format = new VideoFormat(option.Width, option.Height, AVPixelFormat.Bgr24);
            var video_param  = new VideoEncoderParameters()
            {
                FrameRate = new Fraction(option.FPS), BitRate = option.BitRate
            };

            video_encoder = new VideoEncoder(option.EncoderName, video_format, video_param);

            #endregion Video Init

            writer = new MediaWriter(option.OutputPath, false).AddEncoder(video_encoder);

            if (audio_decoder != null)
            {
                audio_encoder = new AudioEncoder(audio_decoder.ID, audio_decoder.OutFormat, BitRate._192Kbps);
                writer.AddEncoder(audio_encoder);
            }

            writer.Initialize();

            Log.User($"Format :{video_format.ToString()}\nVideo Encoder :{video_encoder.ToString()}");

            video_frame = new VideoFrame(video_format);
            audio_frame = new AudioFrame(audio_decoder.OutFormat);

            audio_encoding_thread      = new Thread(AudioEncoding);
            audio_encoding_thread.Name = "Audio Encoder Thread";
            audio_encoding_thread.Start();
        }
        private async Task StopAudioStream()
        {
            if (AudioSource != null)
            {
                DoStopAudioStream();
                await AudioSource.Stop();

                AudioSource.Destroy();
                AudioSource = null;
            }
            if (AudioDepacketizer != null)
            {
                AudioDepacketizer.Destroy();
                AudioDepacketizer = null;
            }
            if (AudioDecoder != null)
            {
                AudioDecoder.Destroy();
                AudioDecoder = null;
            }
            if (ResetAudioPipe != null)
            {
                ResetAudioPipe.Destroy();
                ResetAudioPipe = null;
            }
            if (AudioConverter != null)
            {
                AudioConverter.Destroy();
                AudioConverter = null;
            }
            if (AudioEncoder != null)
            {
                AudioEncoder.Destroy();
                AudioEncoder = null;
            }
            if (AudioPacketizer != null)
            {
                AudioPacketizer.Destroy();
                AudioPacketizer = null;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AudioPlayer" /> class.
        /// </summary>
        /// <param name="xaudio2">The xaudio2 engine.</param>
        /// <param name="audioStream">The input audio stream.</param>
        public AudioPlayer(XAudio2 xaudio2, Stream audioStream)
        {
            _xaudio2 = xaudio2;
            var audioDecoder = new AudioDecoder(audioStream);

            audioStream.Seek(0, SeekOrigin.Begin);
            _indDataStream = ConverStreamToIeeeFloat(new SoundStream(audioStream).ToDataStream());

            _waveFormat = new WaveFormat(audioDecoder.WaveFormat.SampleRate, 32, audioDecoder.WaveFormat.Channels);
            audioDecoder.Dispose();
            _sourceVoice = new SourceVoice(xaudio2, _waveFormat);

            _bufferSize      = _waveFormat.ConvertLatencyToByteSize(7);
            _isConvolutionOn = false;
            _horizontalAngle = 0f;
            _elevation       = 0f;

            _sourceVoice.BufferEnd += sourceVoice_BufferEnd;
            _sourceVoice.Start();

            _bufferEndEvent = new AutoResetEvent(false);
            _playEvent      = new ManualResetEvent(false);

            _convolution = new Convolution();

            // Pre-allocate buffers
            _audioBuffersRing = new AudioBuffer[3];
            _memBuffers       = new DataPointer[_audioBuffersRing.Length];
            for (int i = 0; i < _audioBuffersRing.Length; i++)
            {
                _audioBuffersRing[i]   = new AudioBuffer();
                _memBuffers[i].Size    = 32 * 1024; // default size 32Kb
                _memBuffers[i].Pointer = Utilities.AllocateMemory(_memBuffers[i].Size);
            }

            // Initialize to stopped
            State = PlayerState.Stopped;

            // Starts the playing thread
            _playingTask = Task.Factory.StartNew(PlayAsync, TaskCreationOptions.LongRunning);
        }
Exemple #16
0
        //-------------------------------------------------
        #region Constructor's Region
        /// <summary>
        /// Initializes a new instance of the <see cref="WotoAudioPlayer" /> class.
        /// </summary>
        /// <param name="xAudio2">The xaudio2 engine.</param>
        /// <param name="audioStream">The input audio stream.</param>
        private WotoAudioPlayer(XAudio2 xAudio2, ref FileStream audioStream)
        {
            try
            {
#pragma warning disable IDE0067
#pragma warning disable IDE0059
                masteringVoice = new MasteringVoice(xAudio2);
#pragma warning restore IDE0059
#pragma warning restore IDE0067
                xaudio2      = xAudio2;
                audioDecoder = new AudioDecoder(audioStream);
                sourceVoice  = new SourceVoice(xAudio2, audioDecoder.WaveFormat);
                localVolume  = DEFAULT_VOLUME;

                // runnig primary start
                PrimaryStart();
            }
            catch
            {
            }
        }
Exemple #17
0
        private void CleanUp()
        {
            if (rtpReceiver != null)
            {
                rtpReceiver.RtpPacketReceived -= RtpReceiver_RtpPacketReceived;
                rtpReceiver.Stop();
            }

            if (wavePlayer != null)
            {
                wavePlayer.PlaybackStopped -= WavePlayer_PlaybackStopped;
                wavePlayer.Dispose();
                wavePlayer = null;
            }

            if (decoder != null)
            {
                decoder.Close();
                decoder = null;
            }
        }
 private Task StopAudioStream()
 {
     if (AudioDepacketizer != null)
     {
         AudioDepacketizer.Destroy();
         AudioDepacketizer = null;
     }
     if (AudioDecoder != null)
     {
         AudioDecoder.Destroy();
         AudioDecoder = null;
     }
     if (AudioConverter != null)
     {
         AudioConverter.Destroy();
         AudioConverter = null;
     }
     if (ResetAudioPipe != null)
     {
         ResetAudioPipe.Destroy();
         ResetAudioPipe = null;
     }
     if (AudioEncoder != null)
     {
         AudioEncoder.Destroy();
         AudioEncoder = null;
     }
     if (AudioPacketizer != null)
     {
         AudioPacketizer.Destroy();
         AudioPacketizer = null;
     }
     if (AudioSink != null)
     {
         AudioSink.Destroy();
         AudioSink = null;
     }
     return(Task.CompletedTask);
 }
Exemple #19
0
        /// <summary>
        /// change the stream of the file with the new file stream object
        /// as the parameter.
        /// </summary>
        /// <param name="_file"></param>
        public void ChangeStream(FileStream _file)
        {
            try
            {
                if (notStartedYet)
                {
                    audioDecoder = new AudioDecoder(_file);
                    sourceVoice  = new SourceVoice(xaudio2, audioDecoder.WaveFormat);
                    IsDisposed   = false;
                    PrimaryStart();
                    return;
                }
                else
                {
                    StopInner();
                    //DisposePlayer();
                    xaudio2        = new XAudio2();
                    masteringVoice = new MasteringVoice(xaudio2);
                    audioDecoder   = new AudioDecoder(_file);
                    sourceVoice    = new SourceVoice(xaudio2, audioDecoder.WaveFormat);

                    PrimaryStart();

                    // Pre-allocate buffers
                    //audioBuffersRing = new AudioBuffer[3];
                    //memBuffers = new DataPointer[audioBuffersRing.Length];
                    //for (int i = 0; i < audioBuffersRing.Length; i++)
                    //{
                    //audioBuffersRing[i] = new AudioBuffer();
                    //memBuffers[i].Size = 32 * 1024; // default size 32Kb
                    //memBuffers[i].Pointer = Utilities.AllocateMemory(memBuffers[i].Size);
                    //}
                }
            }
            catch
            {
                return;
            }
        }
 private void AudioThreadFunc()
 {
     try
     {
         int num = 0;
         while (this.audioThreadContinue_)
         {
             AudioDecoder audioDecoder = null;
             List <MediaKitProcessor.OGVControl> obj = this.controls_;
             lock (obj)
             {
                 if (num < this.audioDecoders_.Count)
                 {
                     audioDecoder = this.audioDecoders_[num++];
                 }
                 else
                 {
                     num = 0;
                     if (num < this.audioDecoders_.Count)
                     {
                         audioDecoder = this.audioDecoders_[num++];
                     }
                 }
             }
             if (audioDecoder != null)
             {
                 audioDecoder.InBackground();
             }
             else
             {
                 Thread.Sleep(10);
             }
         }
     }
     catch (Exception ex)
     {
         this.exception_ = ex;
     }
 }
Exemple #21
0
        public static void DecodeAudioToWav(string fileName)
        {
            fileName = "Assets/sounds/" + fileName;
            var stream       = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var audioDecoder = new AudioDecoder(stream);

            var outputWavStream = new FileStream(fileName + ".wav", FileMode.Create, FileAccess.Write);

            var wavWriter = new WavWriter(outputWavStream);

            // Write the WAV file
            wavWriter.Begin(audioDecoder.WaveFormat);

            // Decode the samples from the input file and output PCM raw data to the WAV stream.
            wavWriter.AppendData(audioDecoder.GetSamples());

            // Close the wav writer.
            wavWriter.End();

            audioDecoder.Dispose();
            outputWavStream.Close();
            stream.Close();
        }
    public KinectReceiver(Material azureKinectScreenMaterial, AzureKinectScreen azureKinectScreen)
    {
        this.azureKinectScreenMaterial = azureKinectScreenMaterial;
        this.azureKinectScreen         = azureKinectScreen;

        textureGroup = new TextureGroup(Plugin.texture_group_reset());

        udpSocket         = null;
        receiverStopped   = false;
        videoMessageQueue = new ConcurrentQueue <Tuple <int, VideoSenderMessageData> >();
        lastVideoFrameId  = -1;

        colorDecoder = null;
        depthDecoder = null;
        preapared    = false;

        ringBuffer       = new RingBuffer((int)(KH_LATENCY_SECONDS * 2 * KH_BYTES_PER_SECOND / sizeof(float)));
        audioDecoder     = new AudioDecoder(KH_SAMPLE_RATE, KH_CHANNEL_COUNT);
        lastAudioFrameId = -1;

        videoMessages  = new Dictionary <int, VideoSenderMessageData>();
        frameStopWatch = Stopwatch.StartNew();
    }
        public void SeekTest()
        {
            var r     = new AudioDecoder(new DecoderSettings(), "alac.m4a");
            var buff1 = new AudioBuffer(r, 16536);
            var buff2 = new AudioBuffer(r, 16536);

            Assert.AreEqual(0, r.Position);
            r.Read(buff1, 7);
            Assert.AreEqual(7, r.Position);
            r.Position = 0;
            Assert.AreEqual(0, r.Position);
            r.Read(buff2, 7);
            Assert.AreEqual(7, r.Position);
            AudioBufferTest.AreEqual(buff1, buff2);
            r.Read(buff1, 7);
            Assert.AreEqual(7 + 7, r.Position);
            r.Position = 7;
            Assert.AreEqual(7, r.Position);
            r.Read(buff2, 7);
            Assert.AreEqual(7 + 7, r.Position);
            AudioBufferTest.AreEqual(buff1, buff2);
            r.Close();
        }
Exemple #24
0
        public void Setup(AudioEncoderSettings inputPars, NetworkSettings networkPars)
        {
            logger.Debug("AudioReceiver::Setup(...)");

            try
            {
                decoder = new AudioDecoder();

                decoder.Open(inputPars);

                waveFormat = new WaveFormat(8000, 16, 1);

                var _deviceId = inputPars.DeviceId;

                Guid deviceId = Guid.Empty;
                if (!string.IsNullOrEmpty(_deviceId))
                {
                    Guid.TryParse(_deviceId, out deviceId);
                }

                DirectSoundDeviceInfo deviceInfo = null;
                var DSDevices = DirectSoundOut.Devices;
                if (DSDevices != null && DSDevices.Count() > 0)
                {
                    //DirectSoundOut.DSDEVID_DefaultPlayback
                    deviceInfo = DSDevices.FirstOrDefault(d => d.Guid == deviceId) ?? DSDevices.FirstOrDefault();
                }

                if (deviceId == null)
                {
                    throw new Exception("Audio device not found...");
                }


                if (deviceInfo != null)
                {
                    logger.Info(deviceInfo.Description + " " + deviceInfo.ModuleName + " " + deviceInfo.Guid);

                    wavePlayer = new NAudio.Wave.DirectSoundOut(deviceInfo.Guid);
                    //wavePlayer = new NAudio.Wave.WaveOut();

                    wavePlayer.PlaybackStopped += WavePlayer_PlaybackStopped;



                    waveBuffer = new BufferedWaveProvider(waveFormat)
                    {
                        BufferDuration = TimeSpan.FromMilliseconds(300),

                        //BufferDuration = TimeSpan.FromMilliseconds(300),
                        DiscardOnBufferOverflow = true
                    };

                    volumeProvider = new VolumeSampleProvider(waveBuffer.ToSampleProvider());

                    var meteringSampleProvider = new MeteringSampleProvider(volumeProvider);

                    meteringSampleProvider.StreamVolume += PostVolumeMeter_StreamVolume;

                    wavePlayer.Init(meteringSampleProvider);


                    bufferLost = false;
                }
                else
                {
                    throw new Exception("DirectSound devices is not available...");
                }


                session = new PCMUSession();

                if (networkPars.TransportMode == TransportMode.Tcp)
                {
                    rtpReceiver = new RtpTcpReceiver(session);
                }
                else
                {
                    rtpReceiver = new RtpUdpReceiver(session);
                }

                session.SSRC = networkPars.SSRC;


                rtpReceiver.Open(networkPars);
                rtpReceiver.RtpPacketReceived += RtpReceiver_RtpPacketReceived;
            }
            catch (Exception ex)
            {
                logger.Debug(ex);
                CleanUp();

                throw;
            }
        }
Exemple #25
0
 /// <summary>
 ///   Loads a signal from a file, such as a ".wav" file.
 /// </summary>
 ///
 /// <param name="fileName">Name of the file to be read.</param>
 ///
 /// <returns>The signal that has been read from the file.</returns>
 ///
 public static Signal FromFile(string fileName)
 {
     return(AudioDecoder.DecodeFromFile(fileName));
 }
Exemple #26
0
        void MountBlobs()
        {
            IBlob file_blob = null;

            BlobInfos = new List<BlobInfo>();
            foreach (var ccf in IN_CompileJob.OUT_CompiledCueFiles)
            {
                var bi = new BlobInfo();
                BlobInfos.Add(bi);

                switch (ccf.Type)
                {
                    case CompiledCueFileType.BIN:
                    case CompiledCueFileType.Unknown:
                        {
                            //raw files:
                            var blob = new Disc.Blob_RawFile { PhysicalPath = ccf.FullPath };
                            OUT_Disc.DisposableResources.Add(file_blob = blob);
                            bi.Length = blob.Length;
                            break;
                        }
                    case CompiledCueFileType.ECM:
                        {
                            var blob = new Disc.Blob_ECM();
                            OUT_Disc.DisposableResources.Add(file_blob = blob);
                            blob.Load(ccf.FullPath);
                            bi.Length = blob.Length;
                            break;
                        }
                    case CompiledCueFileType.WAVE:
                        {
                            var blob = new Disc.Blob_WaveFile();
                            OUT_Disc.DisposableResources.Add(file_blob = blob);
                            blob.Load(ccf.FullPath);
                            bi.Length = blob.Length;
                            break;
                        }
                    case CompiledCueFileType.DecodeAudio:
                        {
                            FFMpeg ffmpeg = new FFMpeg();
                            if (!ffmpeg.QueryServiceAvailable())
                            {
                                throw new DiscReferenceException(ccf.FullPath, "No decoding service was available (make sure ffmpeg.exe is available. even though this may be a wav, ffmpeg is used to load oddly formatted wave files. If you object to this, please send us a note and we'll see what we can do. It shouldn't be too hard.)");
                            }
                            AudioDecoder dec = new AudioDecoder();
                            byte[] buf = dec.AcquireWaveData(ccf.FullPath);
                            var blob = new Disc.Blob_WaveFile();
                            OUT_Disc.DisposableResources.Add(file_blob = blob);
                            blob.Load(new MemoryStream(buf));
                            bi.Length = buf.Length;
                            break;
                        }
                    default:
                        throw new InvalidOperationException();
                } //switch(file type)

                //wrap all the blobs with zero padding
                bi.Blob = new Disc.Blob_ZeroPadAdapter(file_blob, bi.Length);
            }
        }
Exemple #27
0
        public static void Play(string fileName)
        {
            if (!Music.Stopped && Music.m_FileName == fileName)
            {
                return;
            }
            if (Music.m_XAudio2 == null)
            {
                MediaFactory.Startup(131184, 1);
                Music.m_XAudio2 = new SharpDX.XAudio2.XAudio2();
                Music.m_XAudio2.StartEngine();
                Music.m_MasteringVoice = new MasteringVoice(Music.m_XAudio2, 0, 0, 0);
                Music.m_AudioDecoder   = new AudioDecoder();
                Music.m_PlayingTask    = Task.Factory.StartNew(new System.Action(Music.PlayAsync), TaskCreationOptions.LongRunning);
            }
            string path = Engine.FileManager.ResolveMUL(string.Format("music/{0}", (object)fileName));

            if (!File.Exists(path))
            {
                return;
            }
            if (!Music.Stopped)
            {
                Music.Stop();
            }
            Music.m_FileName   = fileName;
            Music.m_FileStream = new NativeFileStream(path, (NativeFileMode)3, 0, (NativeFileShare)1);
            Music.m_AudioDecoder.SetSourceStream((Stream)Music.m_FileStream);
            if (Music.m_SourceVoice == null)
            {
                Music.m_SourceVoice            = new SourceVoice(Music.m_XAudio2, Music.m_AudioDecoder.WaveFormat);
                Music.m_SourceVoice.BufferEnd += (new System.Action <IntPtr>(Music.SourceVoice_BufferEnd));
            }
            Music.m_SourceVoice.Start();
            Music.m_AudioBuffers  = new AudioBuffer[3];
            Music.m_MemoryBuffers = new DataPointer[Music.m_AudioBuffers.Length];
            for (int index = 0; index < Music.m_AudioBuffers.Length; ++index)
            {
                Music.m_AudioBuffers[index]          = new AudioBuffer();
                Music.m_MemoryBuffers[index].Size    = 32768;
                Music.m_MemoryBuffers[index].Pointer = Utilities.AllocateMemory((int)Music.m_MemoryBuffers[index].Size, 16);
            }
            PlayUO.Volume volume = Preferences.Current.Music.Volume;
            if (volume != null && volume.Mute)
            {
                return;
            }
            if (volume != null)
            {
                ((Voice)Music.m_SourceVoice).SetVolume(1f, 0);
            }
            bool flag = false;

            if (Music.Stopped)
            {
                ++Music.m_PlayCounter;
                Music.m_WaitForPlayToOutput.Reset();
                flag = true;
            }
            else
            {
                Music.m_Clock.Start();
            }
            Music.m_State = (PMediaPlayerState)2;
            Music.m_PlayEvent.Set();
            if (!flag)
            {
                return;
            }
            Music.m_WaitForPlayToOutput.WaitOne();
        }
Exemple #28
0
        void MountBlobs()
        {
            IBlob file_blob = null;

            BlobInfos = new List <BlobInfo>();
            foreach (var ccf in IN_CompileJob.OUT_CompiledCueFiles)
            {
                var bi = new BlobInfo();
                BlobInfos.Add(bi);

                switch (ccf.Type)
                {
                case CompiledCueFileType.BIN:
                case CompiledCueFileType.Unknown:
                {
                    //raw files:
                    var blob = new Disc.Blob_RawFile {
                        PhysicalPath = ccf.FullPath
                    };
                    OUT_Disc.DisposableResources.Add(file_blob = blob);
                    bi.Length = blob.Length;
                    break;
                }

                case CompiledCueFileType.ECM:
                {
                    var blob = new Disc.Blob_ECM();
                    OUT_Disc.DisposableResources.Add(file_blob = blob);
                    blob.Load(ccf.FullPath);
                    bi.Length = blob.Length;
                    break;
                }

                case CompiledCueFileType.WAVE:
                {
                    var blob = new Disc.Blob_WaveFile();
                    OUT_Disc.DisposableResources.Add(file_blob = blob);
                    blob.Load(ccf.FullPath);
                    bi.Length = blob.Length;
                    break;
                }

                case CompiledCueFileType.DecodeAudio:
                {
                    FFMpeg ffmpeg = new FFMpeg();
                    if (!ffmpeg.QueryServiceAvailable())
                    {
                        throw new DiscReferenceException(ccf.FullPath, "No decoding service was available (make sure ffmpeg.exe is available. even though this may be a wav, ffmpeg is used to load oddly formatted wave files. If you object to this, please send us a note and we'll see what we can do. It shouldn't be too hard.)");
                    }
                    AudioDecoder dec  = new AudioDecoder();
                    byte[]       buf  = dec.AcquireWaveData(ccf.FullPath);
                    var          blob = new Disc.Blob_WaveFile();
                    OUT_Disc.DisposableResources.Add(file_blob = blob);
                    blob.Load(new MemoryStream(buf));
                    bi.Length = buf.Length;
                    break;
                }

                default:
                    throw new InvalidOperationException();
                }                 //switch(file type)

                //wrap all the blobs with zero padding
                bi.Blob = new Disc.Blob_ZeroPadAdapter(file_blob, bi.Length);
            }
        }
Exemple #29
0
        static int Main(string[] args)
        {
            TextWriter stdout = Console.Out;

            Console.SetOut(Console.Error);

            var settings = new Codecs.FLACCL.EncoderSettings()
            {
                AllowNonSubset = true
            };
            TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
            bool     debug = false, quiet = false;
            string   stereo_method = null;
            string   window_function = null;
            string   input_file = null;
            string   output_file = null;
            string   device_type = null;
            int      min_precision = -1, max_precision = -1,
                     orders_per_window = -1, orders_per_channel = -1;
            int  input_len = 4096, input_val = 0, input_bps = 16, input_ch = 2, input_rate = 44100;
            int  level = -1, vbr_mode = -1;
            bool do_seektable    = true;
            bool estimate_window = false;
            bool buffered        = false;
            bool ok                 = true;
            bool allowNonSubset     = false;
            bool ignore_chunk_sizes = false;
            int  intarg;

            for (int arg = 0; arg < args.Length; arg++)
            {
                if (args[arg].Length == 0)
                {
                    ok = false;
                }
                else if (args[arg] == "--debug")
                {
                    debug = true;
                }
                else if ((args[arg] == "-q" || args[arg] == "--quiet"))
                {
                    quiet = true;
                }
                else if (args[arg] == "--verify")
                {
                    settings.DoVerify = true;
                }
                else if (args[arg] == "--no-seektable")
                {
                    do_seektable = false;
                }
                else if (args[arg] == "--ignore-chunk-sizes")
                {
                    ignore_chunk_sizes = true;
                }
                else if (args[arg] == "--slow-gpu")
                {
                    settings.GPUOnly = false;
                }
                else if (args[arg] == "--fast-gpu")
                {
                    settings.DoRice = true;
                }
                else if (args[arg] == "--no-md5")
                {
                    settings.DoMD5 = false;
                }
                else if (args[arg] == "--lax")
                {
                    allowNonSubset = true;
                }
                else if (args[arg] == "--buffered")
                {
                    buffered = true;
                }
                else if (args[arg] == "--cpu-threads")
                {
                    int val = settings.CPUThreads;
                    ok = (++arg < args.Length) && int.TryParse(args[arg], out val);
                    settings.CPUThreads = val;
                }
                else if (args[arg] == "--group-size" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    settings.GroupSize = intarg;
                }
                else if (args[arg] == "--task-size" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    settings.TaskSize = intarg;
                }
                else if (args[arg] == "--define" && arg + 2 < args.Length)
                {
                    settings.Defines += "#define " + args[++arg] + " " + args[++arg] + "\n";
                }
                else if (args[arg] == "--opencl-platform" && ++arg < args.Length)
                {
                    settings.Platform = args[arg];
                }
                else if (args[arg] == "--mapped-memory")
                {
                    settings.MappedMemory = true;
                }
                else if (args[arg] == "--opencl-type" && ++arg < args.Length)
                {
                    device_type = args[arg];
                }
                else if (args[arg] == "--input-length" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    input_len = intarg;
                }
                else if (args[arg] == "--input-value" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    input_val = intarg;
                }
                else if (args[arg] == "--input-bps" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    input_bps = intarg;
                }
                else if (args[arg] == "--input-channels" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    input_ch = intarg;
                }
                else if ((args[arg] == "-o" || args[arg] == "--output") && ++arg < args.Length)
                {
                    output_file = args[arg];
                }
                else if ((args[arg] == "-s" || args[arg] == "--stereo") && ++arg < args.Length)
                {
                    stereo_method = args[arg];
                }
                else if ((args[arg] == "-w" || args[arg] == "--window") && ++arg < args.Length)
                {
                    window_function = args[arg];
                }
                else if ((args[arg] == "-r" || args[arg] == "--partition-order") && ++arg < args.Length)
                {
                    int min_partition_order, max_partition_order;
                    ok = (args[arg].Split(',').Length == 2 &&
                          int.TryParse(args[arg].Split(',')[0], out min_partition_order) &&
                          (settings.MinPartitionOrder = min_partition_order) != -1 &&
                          int.TryParse(args[arg].Split(',')[1], out max_partition_order) &&
                          (settings.MaxPartitionOrder = max_partition_order) != -1) ||
                         (int.TryParse(args[arg], out max_partition_order) &&
                          (settings.MaxPartitionOrder = max_partition_order) != -1);
                }
                else if ((args[arg] == "-l" || args[arg] == "--lpc-order") && ++arg < args.Length)
                {
                    int min_lpc_order, max_lpc_order;
                    ok = (args[arg].Split(',').Length == 2 &&
                          int.TryParse(args[arg].Split(',')[0], out min_lpc_order) &&
                          (settings.MinLPCOrder = min_lpc_order) != -1 &&
                          int.TryParse(args[arg].Split(',')[1], out max_lpc_order) &&
                          (settings.MaxLPCOrder = max_lpc_order) != -1) ||
                         (int.TryParse(args[arg], out max_lpc_order) &&
                          (settings.MaxLPCOrder = max_lpc_order) != -1);
                }
                else if (args[arg] == "--fixed-order" && ++arg < args.Length)
                {
                    int min_fixed_order, max_fixed_order;
                    ok = (args[arg].Split(',').Length == 2 &&
                          int.TryParse(args[arg].Split(',')[0], out min_fixed_order) &&
                          (settings.MinFixedOrder = min_fixed_order) != -1 &&
                          int.TryParse(args[arg].Split(',')[1], out max_fixed_order) &&
                          (settings.MaxFixedOrder = max_fixed_order) != -1) ||
                         (int.TryParse(args[arg], out max_fixed_order) &&
                          (settings.MaxFixedOrder = max_fixed_order) != -1);
                }
                else if ((args[arg] == "-c" || args[arg] == "--max-precision") && ++arg < args.Length)
                {
                    ok = (args[arg].Split(',').Length == 2 &&
                          int.TryParse(args[arg].Split(',')[0], out min_precision) &&
                          int.TryParse(args[arg].Split(',')[1], out max_precision)) ||
                         int.TryParse(args[arg], out max_precision);
                }
                else if ((args[arg] == "-v" || args[arg] == "--vbr"))
                {
                    ok = (++arg < args.Length) && int.TryParse(args[arg], out vbr_mode);
                }
                else if (args[arg] == "--orders-per-window" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    orders_per_window = intarg;
                }
                else if (args[arg] == "--orders-per-channel" && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    orders_per_channel = intarg;
                }
                else if (args[arg] == "--estimate-window")
                {
                    estimate_window = true;
                }
                else if ((args[arg] == "-b" || args[arg] == "--blocksize") && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    settings.BlockSize = intarg;
                }
                else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length && int.TryParse(args[arg], out intarg))
                {
                    settings.Padding = intarg;
                }
                else if (args[arg] != "-" && args[arg][0] == '-' && int.TryParse(args[arg].Substring(1), out level))
                {
                    ok = level >= 0 && level <= 11;
                    settings.SetEncoderModeIndex(level);
                }
                else if ((args[arg][0] != '-' || args[arg] == "-") && input_file == null)
                {
                    input_file = args[arg];
                }
                else
                {
                    ok = false;
                }
                if (!ok)
                {
                    break;
                }
            }
            if (!quiet)
            {
                Console.WriteLine("{0}, Copyright (C) 2010-2021 Grigory Chudov.", Codecs.FLACCL.AudioEncoder.Vendor);
                Console.WriteLine("This is free software under the GNU GPLv3+ license; There is NO WARRANTY, to");
                Console.WriteLine("the extent permitted by law. <http://www.gnu.org/licenses/> for details.");
            }
            if (!ok || input_file == null)
            {
                Usage();
                return(1);
            }

            if (((input_file == "-" || Path.GetExtension(input_file) == ".flac") && output_file == null))
            {
                Usage();
                Console.WriteLine();
                Console.WriteLine("Output file not specified.");
                return(2);
            }

            IAudioSource audioSource;

            try
            {
                if (input_file == "-")
                {
                    audioSource = new Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings()
                    {
                        IgnoreChunkSizes = true
                    }, "", Console.OpenStandardInput());
                }
                else if (input_file == "nul")
                {
                    audioSource = new Codecs.NULL.AudioDecoder(new AudioPCMConfig(input_bps, input_ch, input_rate), input_len, input_val);
                }
                else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".wav")
                {
                    audioSource = new Codecs.WAV.AudioDecoder(new Codecs.WAV.DecoderSettings(), input_file);
                }
                else if (File.Exists(input_file) && Path.GetExtension(input_file) == ".flac")
                {
                    audioSource = new AudioDecoder(new DecoderSettings(), input_file);
                }
                else
                {
                    Usage();
                    Console.WriteLine();
                    Console.WriteLine("Input file \"{0}\" does not exist.", input_file);
                    return(2);
                }
            }
            catch (Exception ex)
            {
                Usage();
                Console.WriteLine("");
                Console.WriteLine("Error: {0}.", ex.Message);
                return(3);
            }
            if (buffered)
            {
                audioSource = new AudioPipe(audioSource, Codecs.FLACCL.AudioEncoder.MAX_BLOCKSIZE);
            }
            if (output_file == null)
            {
                output_file = Path.ChangeExtension(input_file, "flac");
            }
            settings.PCM            = audioSource.PCM;
            settings.AllowNonSubset = allowNonSubset;
            Codecs.FLACCL.AudioEncoder encoder;

            try
            {
                if (device_type != null)
                {
                    settings.DeviceType = (OpenCLDeviceType)(Enum.Parse(typeof(OpenCLDeviceType), device_type, true));
                }
                encoder = new Codecs.FLACCL.AudioEncoder((output_file == "-" || output_file == "nul") ? "" : output_file,
                                                         output_file == "-" ? Console.OpenStandardOutput() :
                                                         output_file == "nul" ? new NullStream() : null,
                                                         settings);
                settings = encoder.Settings as Codecs.FLACCL.EncoderSettings;
                encoder.FinalSampleCount = audioSource.Length;
                if (stereo_method != null)
                {
                    encoder.StereoMethod = FlakeConstants.LookupStereoMethod(stereo_method);
                }
                if (window_function != null)
                {
                    encoder.WindowFunction = FlakeConstants.LookupWindowFunction(window_function);
                }
                if (max_precision >= 0)
                {
                    encoder.MaxPrecisionSearch = max_precision;
                }
                if (min_precision >= 0)
                {
                    encoder.MinPrecisionSearch = min_precision;
                }
                if (vbr_mode >= 0)
                {
                    encoder.VBRMode = vbr_mode;
                }
                if (orders_per_window >= 0)
                {
                    encoder.OrdersPerWindow = orders_per_window;
                }
                if (orders_per_channel >= 0)
                {
                    encoder.OrdersPerChannel = orders_per_channel;
                }
                if (estimate_window)
                {
                    encoder.EstimateWindow = estimate_window;
                }
                encoder.DoSeekTable = do_seektable;
            }
            catch (Exception ex)
            {
                Usage();
                Console.WriteLine("");
                Console.WriteLine("Error: {0}.", ex.Message);
                return(3);
            }

            IAudioDest  audioDest = encoder;
            AudioBuffer buff      = new AudioBuffer(audioSource, Codecs.FLACCL.AudioEncoder.MAX_BLOCKSIZE);

            if (!quiet)
            {
                Console.WriteLine("Filename  : {0}", input_file);
                Console.WriteLine("File Info : {0} Hz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample, TimeSpan.FromSeconds(audioSource.Length * 1.0 / audioSource.PCM.SampleRate));
                Console.WriteLine("Device    : {0}, Platform: \"{1}\", Version: {2}, Driver: {3}", settings.Device.Trim(), settings.Platform, settings.PlatformVersion.Trim(), settings.DriverVersion.Trim());
            }

            bool keepRunning = true;

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                keepRunning = false;
                if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                {
                    e.Cancel = true;
                }
                else
                {
                    audioDest.Delete();
                }
            };

            DateTime start = DateTime.Now;

            try
            {
                audioDest.Write(buff);
                start = DateTime.Now;
                while (audioSource.Read(buff, -1) != 0)
                {
                    audioDest.Write(buff);
                    TimeSpan elapsed = DateTime.Now - start;
                    if (!quiet)
                    {
                        if ((elapsed - lastPrint).TotalMilliseconds > 60)
                        {
                            long length = Math.Max(audioSource.Position, audioSource.Length);
                            Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
                                                100.0 * audioSource.Position / length,
                                                audioSource.Position / elapsed.TotalSeconds / audioSource.PCM.SampleRate,
                                                elapsed,
                                                TimeSpan.FromMilliseconds(elapsed.TotalMilliseconds / audioSource.Position * length)
                                                );
                            lastPrint = elapsed;
                        }
                    }
                    if (!keepRunning)
                    {
                        throw new Exception("Aborted");
                    }
                }
                audioDest.Close();
            }
            catch (OpenCLNet.OpenCLBuildException ex)
            {
                Console.Error.Write("\r                                                                         \r");
                Console.WriteLine("Error     : {0}", ex.Message);
                Console.WriteLine("{0}", ex.BuildLogs[0]);
                if (debug)
                {
                    using (StreamWriter sw = new StreamWriter("debug.txt", true))
                        sw.WriteLine("{0}\n{1}\n{2}", ex.Message, ex.StackTrace, ex.BuildLogs[0]);
                }
                audioDest.Delete();
                audioSource.Close();
                return(4);
            }
#if !DEBUG
            catch (Exception ex)
            {
                Console.Error.Write("\r                                                                         \r");
                Console.WriteLine("Error     : {0}", ex.Message);
                if (debug)
                {
                    using (StreamWriter sw = new StreamWriter("debug.txt", true))
                        sw.WriteLine("{0}\n{1}", ex.Message, ex.StackTrace);
                }
                audioDest.Delete();
                audioSource.Close();
                return(4);
            }
#endif

            TimeSpan totalElapsed = DateTime.Now - start;
            if (!quiet)
            {
                Console.Error.Write("\r                                                                         \r");
                Console.WriteLine("Results   : {0:0.00}x; {2} bytes in {1} seconds;",
                                  audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
                                  totalElapsed,
                                  encoder.TotalSize
                                  );
            }
            audioSource.Close();

            if (debug)
            {
                Console.SetOut(stdout);
                Console.Out.WriteLine("{0}\t{1}\t{2}\t{3}\t{4} ({5})\t{6}/{7}+{12}{13}\t{8}..{9}\t{10}\t{11}",
                                      encoder.TotalSize,
                                      encoder.UserProcessorTime.TotalSeconds > 0 ? encoder.UserProcessorTime.TotalSeconds : totalElapsed.TotalSeconds,
                                      (encoder.StereoMethod.ToString() + (encoder.OrdersPerChannel == 32 ? "" : "(" + encoder.OrdersPerChannel.ToString() + ")")).PadRight(15),
                                      encoder.WindowFunction.ToString().PadRight(15),
                                      settings.MaxPartitionOrder,
                                      settings.GPUOnly ? "GPU" : "CPU",
                                      encoder.OrdersPerWindow,
                                      settings.MaxLPCOrder,
                                      encoder.MinPrecisionSearch,
                                      encoder.MaxPrecisionSearch,
                                      encoder.Settings.BlockSize,
                                      encoder.VBRMode,
                                      settings.MaxFixedOrder - settings.MinFixedOrder + 1,
                                      encoder.DoConstant ? "c" : ""
                                      );
            }
            return(0);
        }
Exemple #30
0
 public AudioStream(Stream stream)
 {
     media   = new MediaReader(stream);
     decoder = media.Decoders.OfType <AudioDecoder>().First();
 }
        public SoundBufferedDataSource(FileInfo FileName)
        {
            //Extract the data from the sound file, and create a buffer with them

            //Creating the source, was not existing
            Volume = 1.0f;

            SoundStream soundstream;

            switch (FileName.Extension)
            {
            case ".wav":
                //Load the sound and bufferize it
                soundstream = new SoundStream(File.OpenRead(FileName.FullName));
                WaveFormat  = soundstream.Format;
                AudioBuffer = new AudioBuffer()
                {
                    Stream     = soundstream.ToDataStream(),
                    AudioBytes = (int)soundstream.Length,
                    Flags      = BufferFlags.EndOfStream
                };

                soundstream.Close();
                soundstream.Dispose();
                break;

            case ".wma":     // NOT good idea this can be HUGE buffer, better streaming a WMA file !
                //New data stream
                using (FileStream fileStream = new FileStream(FileName.FullName, FileMode.Open, FileAccess.Read))
                {
                    var audioDecoder    = new AudioDecoder(fileStream);
                    var outputWavStream = new MemoryStream();

                    var wavWriter = new WavWriter(outputWavStream);

                    // Write the WAV file
                    wavWriter.Begin(audioDecoder.WaveFormat);
                    // Decode the samples from the input file and output PCM raw data to the WAV stream.
                    wavWriter.AppendData(audioDecoder.GetSamples());
                    // Close the wav writer.
                    wavWriter.End();

                    outputWavStream.Position = 0;
                    soundstream = new SoundStream(outputWavStream);

                    WaveFormat  = soundstream.Format;
                    AudioBuffer = new AudioBuffer()
                    {
                        Stream     = soundstream.ToDataStream(),
                        AudioBytes = (int)soundstream.Length,
                        Flags      = BufferFlags.EndOfStream
                    };

                    soundstream.Close();
                    soundstream.Dispose();
                    outputWavStream.Dispose();
                    audioDecoder.Dispose();
                }

                break;

            default:
                break;
            }
        }