Ejemplo n.º 1
0
 /// <summary>
 /// Dispose
 /// </summary>
 public void Dispose()
 {
     _voice.DestroyVoice();
     _voice.Dispose();
     _stream.Dispose();
     _buffer.Stream.Dispose();
 }
Ejemplo n.º 2
0
        public void Update(Camera camera)
        {
            if (camera != null)
            {
                UpdateListener(camera);
            }

            if (_currentTrack != null && !_currentTrack.IsPlaying)
            {
                _musicTrackFinishedCounts.TryGetValue(_currentTrackName, out var count);
                _musicTrackFinishedCounts[_currentTrackName] = count + 1;
                _currentTrack.Dispose();
                _currentTrack     = null;
                _currentTrackName = null;
            }
        }
Ejemplo n.º 3
0
 public void Dispose()
 {
     _sourceVoice?.DestroyVoice();
     _sourceVoice?.Dispose();
     _buffer.Stream.Dispose();
     _stream?.Dispose();
 }
Ejemplo n.º 4
0
        /// <summary>
        ///   Worker thread.
        /// </summary>
        ///
        private void WorkerThread()
        {
            SoundStream waveStream = null;

            try
            {
                waveStream = (stream != null)
                    ? new SoundStream(stream)
                    : new SoundStream(File.OpenRead(fileName));

                // Open the Wave stream
                decoder.Open(waveStream);

                while (stopEvent.WaitOne(0, false))
                {
                    // get next frame
                    Signal s = decoder.Decode(frameSize);
                    framesReceived += s.Length;
                    bytesReceived  += decoder.Bytes;

                    if (NewFrame != null)
                    {
                        NewFrame(this, new NewFrameEventArgs(s));
                    }

                    // check current position
                    if (waveStream.Position >= waveStream.Length)
                    {
                        break;
                    }

                    // sleeping ...
                    Thread.Sleep(100);
                }
            }
            catch (Exception exception)
            {
                // provide information to clients
                if (AudioSourceError != null)
                {
                    AudioSourceError(this, new AudioSourceErrorEventArgs(exception.Message));
                }
                else
                {
                    throw;
                }
            }

            if (waveStream != null)
            {
                waveStream.Close();
                waveStream.Dispose();
                waveStream = null;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///   Worker thread.
        /// </summary>
        ///
        private void WorkerThread()
        {
            this.shouldStop = false;

            SoundStream waveStream = null;

            try
            {
                waveStream = (stream != null) ?
                             new SoundStream(stream) : new SoundStream(File.OpenRead(fileName));

                // Open the Wave stream
                decoder.Open(waveStream);

                Signal signal = null;
                while (!this.shouldStop)
                {
                    // get next frame, overwriting the previous
                    signal          = decoder.Decode(frameSize, signal);
                    framesReceived += signal.NumberOfFrames;
                    bytesReceived  += decoder.NumberOfBytesRead;

                    if (NewFrame != null)
                    {
                        NewFrame(this, new NewFrameEventArgs(signal));
                    }

                    // check current position
                    if (waveStream.Position >= waveStream.Length)
                    {
                        this.shouldStop = true;
                    }
                }
            }
            catch (Exception exception)
            {
                // provide information to clients
                if (AudioSourceError == null)
                {
                    throw;
                }

                AudioSourceError(this, new AudioSourceErrorEventArgs(exception));
            }

            if (waveStream != null)
            {
                waveStream.Close();
                waveStream.Dispose();
                waveStream = null;
            }
        }
Ejemplo n.º 6
0
        public void Dispose()
        {
            if (_voice != null && !_voice.IsDisposed)
            {
                _voice.DestroyVoice();
                _voice.Dispose();
            }

            if (_stream != null)
            {
                _stream.Dispose();
            }
        }
Ejemplo n.º 7
0
        public void Reuse()
        {
            var mp3Stream = typeof(SoundStreams).Assembly.GetManifestResourceStream("SharpAudio.Tests.Assets.test.mp3");

            using (var engine = AudioEngine.CreateDefault())
            {
                var soundStream = new SoundStream(mp3Stream, new SoundSink(engine));

                soundStream.Play();
                soundStream.Dispose();

                mp3Stream          = typeof(SoundStreams).Assembly.GetManifestResourceStream("SharpAudio.Tests.Assets.test.mp3");
                soundStream        = new SoundStream(mp3Stream, new SoundSink(engine));
                soundStream.Volume = 1.0f;
            }
        }
Ejemplo n.º 8
0
        public void Dispose()
        {
            if (_stream != null)
            {
                _stream.Dispose();
            }
            _stream = null;

            if (_bufferList != null)
            {
                for (int i = 0; i < _bufferList.Count; i++)
                {
                    _bufferList[i].Dispose();
                }
            }
            _bufferList = null;

            _loop = false;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a new instance of the <see cref="SoundEffect"/> class from the spefified data stream.
        /// </summary>
        /// <param name="audioManager">The audio manager associated to the created instance.</param>
        /// <param name="stream">The stream containing the data from which to create the effect.</param>
        /// <param name="name">The name of the effect (optional).</param>
        /// <returns>The created effect.</returns>
        public static SoundEffect FromStream(AudioManager audioManager, Stream stream, string name = null)
        {
            if (audioManager == null)
            {
                throw new ArgumentNullException("audioManager");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            var sound              = new SoundStream(stream);
            var format             = sound.Format;
            var decodedPacketsInfo = sound.DecodedPacketsInfo;
            var buffer             = sound.ToDataStream();

            sound.Dispose();

            return(audioManager.ToDisposeAudioAsset(new SoundEffect(audioManager, name, format, buffer, decodedPacketsInfo)));
        }
Ejemplo n.º 10
0
 public void Dispose()
 {
     if (_xAudio2 != null)
     {
         _xAudio2.Dispose();
     }
     if (_soundStream != null)
     {
         _soundStream.Dispose();
     }
     if (_nativeFilestream != null)
     {
         _nativeFilestream.Dispose();
     }
     if (_sourceVoice != null)
     {
         _sourceVoice.Dispose();
     }
     if (_masteringVoice != null)
     {
         _masteringVoice.Dispose();
     }
 }
Ejemplo n.º 11
0
        public SoundView(AssetViewContext context)
        {
            _source = context.Game.Audio.GetStream(context.Entry.FilePath);

            AddDisposeAction(() => _source.Dispose());
        }
Ejemplo n.º 12
0
 public void Dispose()
 {
     m_stream.Dispose();
     m_buffer.Stream.Dispose();
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Creates a new instance of the <see cref="SoundEffect"/> class from the spefified data stream.
        /// </summary>
        /// <param name="audioManager">The audio manager associated to the created instance.</param>
        /// <param name="stream">The stream containing the data from which to create the effect.</param>
        /// <param name="name">The name of the effect (optional).</param>
        /// <returns>The created effect.</returns>
        public static SoundEffect FromStream(AudioManager audioManager, Stream stream, string name = null)
        {
            if (audioManager == null)
                throw new ArgumentNullException("audioManager");

            if (stream == null)
                throw new ArgumentNullException("stream");

            var sound = new SoundStream(stream);
            var format = sound.Format;
            var decodedPacketsInfo = sound.DecodedPacketsInfo;
            var buffer = sound.ToDataStream();

            sound.Dispose();

            return audioManager.ToDisposeAudioAsset(new SoundEffect(audioManager, name, format, buffer, decodedPacketsInfo));
        }
Ejemplo n.º 14
0
 /// <summary>
 ///     Disposes <see cref="SoundStream" /> instance owned by the <see cref="Sound" />. Actual memory will be released when
 ///     all instances of the sound will complete playing and shared instances of <see cref="SharedMemoryStream" /> will be
 ///     disposed.
 /// </summary>
 public void Dispose()
 {
     SoundStream.Dispose();
 }
Ejemplo n.º 15
0
        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;
            }
        }
Ejemplo n.º 16
0
        public static void RecordTrack(GLWindow game, bool is1080P)
        {
            var flag = game.Track.GetFlag();

            if (flag == null)
            {
                return;
            }
            var resolution = new Size(is1080P ? 1920 : 1280, is1080P ? 1080 : 720);
            var oldsize    = game.RenderSize;
            var invalid    = false;
            var state      = new Rider();

            game.Track.Reset(state);
            var frame = flag.Frame;

            Recording      = true;
            Recording1080p = is1080P;
            game.Canvas.SetSize(game.RenderSize.Width, game.RenderSize.Height);
            game.Canvas.FindChildByName("buttons").Position(Pos.CenterH);

            if (frame > 400)                  //many frames, will likely lag the game. Update the window as a fallback.
            {
                if (frame > (20 * (60 * 40))) //too many frames, could lag the game very bad.
                {
                    return;
                }
                game.Title = Program.WindowTitle + " [Validating flag]";
                game.ProcessEvents();
            }
            for (var i = 0; i < frame; i++)
            {
                game.Track.Tick(state);
            }
            for (var i = 0; i < state.ModelAnchors.Length; i++)
            {
                if (state.ModelAnchors[i].Position != flag.State.ModelAnchors[i].Position ||
                    state.ModelAnchors[i].Prev != flag.State.ModelAnchors[i].Prev)
                {
                    invalid = true;
                    break;
                }
            }
            var frontbuffer = SafeFrameBuffer.GenFramebuffer();

            SafeFrameBuffer.BindFramebuffer(FramebufferTarget.Framebuffer, frontbuffer);

            var rbo2 = SafeFrameBuffer.GenRenderbuffer();

            SafeFrameBuffer.BindRenderbuffer(RenderbufferTarget.Renderbuffer, rbo2);
            SafeFrameBuffer.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.Rgb8, resolution.Width, resolution.Height);
            SafeFrameBuffer.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, RenderbufferTarget.Renderbuffer, rbo2);

            SafeFrameBuffer.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);
            if (!invalid)
            {
                string errormessage = "An unknown error occured during recording.";
                game.Title = Program.WindowTitle + " [Recording | Hold ESC to cancel]";
                game.ProcessEvents();
                var filename   = Program.CurrentDirectory + game.Track.Name + ".mp4";
                var flagbackup = flag;
                var hardexit   = false;
                game.Track.Flag();
                var recmodesave = game.SettingRecordingMode;
                game.SettingRecordingMode = true;
                game.Track.Start(true, true, false, false);
                game.Render();
                var dir = Program.CurrentDirectory + game.Track.Name + "_rec";
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                var firstframe = GrabScreenshot(game, frontbuffer);
                SaveScreenshot(game.RenderSize.Width, game.RenderSize.Height, firstframe, dir + Path.DirectorySeparatorChar + "tmp" + 0 + ".png");
                int[] savethreads = { 0 };
                for (var i = 0; i < frame; i++)
                {
                    if (hardexit)
                    {
                        break;
                    }
                    game.Track.Update(1);
                    game.Render();
                    var screenshot = GrabScreenshot(game, frontbuffer);
                    var objtopass  = new Tuple <byte[], int>(screenshot, i + 1);
                    savethreads[0] += 1;
                    var save = new Task(t =>
                    {
                        var passed = (Tuple <byte[], int>)t;
                        try
                        {
                            SaveScreenshot(game.RenderSize.Width, game.RenderSize.Height, passed.Item1, dir + Path.DirectorySeparatorChar + "tmp" + passed.Item2 + ".png");
                        }
                        catch
                        {
                            hardexit     = true;
                            errormessage = "An error occured when saving the frame.";
                        }
                        finally
                        {
                            Interlocked.Decrement(ref savethreads[0]);
                        }
                    }, objtopass);

                    save.Start();
                    if (Keyboard.GetState()[Key.Escape])
                    {
                        hardexit     = true;
                        errormessage = "The user manually cancelled recording.";
                    }
                    if (i % 40 == 0)
                    {
                        game.Title = string.Format("{0} [Recording {1:P}% | Hold ESC to cancel]", Program.WindowTitle, i / (double)frame);
                        game.ProcessEvents();
                    }
                }

                if (!hardexit)
                {
                    var parameters = new FFMPEGParameters();
                    parameters.AddOption("framerate", "40");
                    parameters.AddOption("i", "\"" + dir + Path.DirectorySeparatorChar + "tmp%d.png" + "\"");
                    parameters.AddOption("vf", "vflip");//we save images upside down expecting ffmpeg to flip more efficiently.
                    parameters.AddOption("c:v", "libx264");
                    parameters.AddOption("preset", "veryfast");
                    parameters.AddOption("qp", "0");

                    //    parameters.AddOption("scale",is1080p?"1920:1080":"1280:720");
                    parameters.OutputFilePath = filename;
                    var failed = false;
                    while (savethreads[0] != 0)
                    {
                        Thread.Sleep(1);
                    }
                    if (File.Exists(filename))
                    {
                        try
                        {
                            File.Delete(filename);
                        }
                        catch
                        {
                            Program.NonFatalError("A file with the name " + game.Track.Name + ".mp4 already exists");
                            failed       = true;
                            errormessage = "Cannot replace a file of the existing name " + game.Track.Name + ".mp4.";
                        }
                    }
                    if (!failed)
                    {
                        game.Title = Program.WindowTitle + " [Encoding Video | 0%]";
                        game.ProcessEvents();
                        try
                        {
                            FFMPEG.Execute(parameters, (string s) =>
                            {
                                int idx = s.IndexOf("frame=", StringComparison.InvariantCulture);
                                if (idx != -1)
                                {
                                    idx += "frame=".Length;
                                    for (; idx < s.Length; idx++)
                                    {
                                        if (char.IsNumber(s[idx]))
                                        {
                                            break;
                                        }
                                    }
                                    var space = s.IndexOf(" ", idx, StringComparison.InvariantCulture);
                                    if (space != -1)
                                    {
                                        var sub       = s.Substring(idx, space - idx);
                                        var parsedint = -1;
                                        if (int.TryParse(sub, out parsedint))
                                        {
                                            game.Title = Program.WindowTitle + string.Format(" [Encoding Video | {0:P}% | Hold ESC to cancel]", parsedint / (double)frame);
                                            game.ProcessEvents();
                                            if (Keyboard.GetState()[Key.Escape])
                                            {
                                                hardexit     = true;
                                                errormessage = "The user manually cancelled recording.";
                                                return(false);
                                            }
                                        }
                                    }
                                }
                                return(true);
                            });
                        }
                        catch (Exception e)
                        {
                            Program.NonFatalError("ffmpeg error.\r\n" + e);
                            hardexit     = true;
                            errormessage = "An ffmpeg error occured.";
                        }
                    }
                }
                try
                {
                    Directory.Delete(dir, true);
                }
                catch
                {
                    Program.NonFatalError("Unable to delete " + dir);
                }
                if (hardexit)
                {
                    try
                    {
                        File.Delete(filename);
                    }
                    catch
                    {
                        Program.NonFatalError("Unable to delete " + filename);
                    }
                }
                game.SettingRecordingMode = recmodesave;
                game.Title = Program.WindowTitle;
                game.Track.RestoreFlag(flagbackup);
                game.Track.Stop();
                game.ProcessEvents();
                var openwindows = game.Canvas.GetOpenWindows();
                foreach (var window in openwindows)
                {
                    var w = window as WindowControl;
                    w?.Close();
                }
                if (File.Exists(filename))
                {
                    try
                    {
                        AudioPlayback.Init();
                        MemoryStream ms = new MemoryStream(GameResources.beep);

                        SoundStream str = new SoundStream(ms);
                        str.Play(0, 1);
                        int count = 0;
                        while (str.Playing)
                        {
                            Thread.Sleep(1);
                            count += 1;
                            if (count >= 3000)//in case something weird happens
                            {
                                break;
                            }
                        }
                        str.Dispose();
                        ms.Dispose();
                    }
                    catch
                    {
                        //ignored
                    }
                }
                else
                {
                    PopupWindow.Error(game.Canvas, game, errormessage, "Error!");
                }
            }
            SafeFrameBuffer.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            SafeFrameBuffer.DeleteFramebuffer(frontbuffer);
            SafeFrameBuffer.DeleteRenderbuffers(1, new[] { rbo2 });
            game.RenderSize = oldsize;
            Recording       = false;

            game.Canvas.SetSize(game.RenderSize.Width, game.RenderSize.Height);
            game.Canvas.FindChildByName("buttons").Position(Pos.CenterH);
        }