Esempio n. 1
0
        void InitMusic()
        {
            if (musicThread != null)
            {
                musicOut.SetVolume(game.MusicVolume / 100.0f); return;
            }

            int musicCount = 0;

            for (int i = 0; i < files.Length; i++)
            {
                if (Utils.CaselessEnds(files[i], ".ogg"))
                {
                    musicCount++;
                }
            }

            musicFiles = new string[musicCount];
            for (int i = 0, j = 0; i < files.Length; i++)
            {
                if (!Utils.CaselessEnds(files[i], ".ogg"))
                {
                    continue;
                }
                musicFiles[j] = files[i]; j++;
            }

            disposingMusic = false;
            musicOut       = GetPlatformOut();
            musicOut.Create(10);
            musicThread = MakeThread(DoMusicThread, "ClassicalSharp.DoMusic");
        }
Esempio n. 2
0
    // Use this for initialization
    void Start()
    {
        // Init Keyboard mapping
        _keyMapping = new Dictionary <KeyCode, EmulatorBase.Button>();
        _keyMapping.Add(KeyCode.UpArrow, EmulatorBase.Button.Up);
        _keyMapping.Add(KeyCode.DownArrow, EmulatorBase.Button.Down);
        _keyMapping.Add(KeyCode.LeftArrow, EmulatorBase.Button.Left);
        _keyMapping.Add(KeyCode.RightArrow, EmulatorBase.Button.Right);
        _keyMapping.Add(KeyCode.Z, EmulatorBase.Button.A);
        _keyMapping.Add(KeyCode.X, EmulatorBase.Button.B);
        _keyMapping.Add(KeyCode.Space, EmulatorBase.Button.Start);
        _keyMapping.Add(KeyCode.LeftShift, EmulatorBase.Button.Select);


        // Load emulator
        IVideoOutput drawable   = new DefaultVideoOutput();
        IAudioOutput audio      = GetComponent <DefaultAudioOutput>();
        ISaveMemory  saveMemory = new DefaultSaveMemory();

        Emulator = new Emulator(drawable, audio, saveMemory);
        ScreenRenderer.material.mainTexture = ((DefaultVideoOutput)Emulator.Video).Texture;

        gameObject.GetComponent <AudioSource>().enabled = false;
        StartCoroutine(LoadRom(Filename));
    }
Esempio n. 3
0
        /// <summary>
        ///   Plays the recorded audio stream.
        /// </summary>
        ///
        private void btnPlay_Click(object sender, EventArgs e)
        {
            // First, we rewind the stream
            stream.Seek(0, SeekOrigin.Begin);

            // Then we create a decoder for it
            decoder = new WaveDecoder(stream);

            // Configure the track bar so the cursor
            // can show the proper current position
            if (trackBar1.Value < decoder.Frames)
            {
                decoder.Seek(trackBar1.Value);
            }
            trackBar1.Maximum = decoder.Samples;

            // Here we can create the output audio device that will be playing the recording
            output = new AudioOutputDevice(this.Handle, decoder.SampleRate, decoder.Channels);

            // Wire up some events
            output.FramePlayingStarted += output_FramePlayingStarted;
            output.NewFrameRequested   += output_NewFrameRequested;
            output.Stopped             += output_PlayingFinished;

            // Start playing!
            output.Play();

            updateButtons();
        }
Esempio n. 4
0
        public override void LoadContent()
        {
            if (!contentLoaded)
            {
                contentLoaded = true;
                spriteBatch   = new SpriteBatch(ScreenManager.GraphicsDevice);

                font         = ScreenManager.Content.Load <SpriteFont>("Fonts/MenuFont");
                inputManager = new XnaInputManager(ScreenManager.Game, info.Game);
                gfx          = new XnaGraphicsManager(info.Game.Width, info.Game.Height, info.Game.PixelFormat, game.Window, ScreenManager.GraphicsDevice);
                ScreenManager.Game.Services.AddService <Core.Graphics.IGraphicsManager>(gfx);
                var saveFileManager = ServiceLocator.SaveFileManager;
#if WINDOWS_UWP
                audioDriver = new XAudio2Mixer();
#else
                audioDriver = new XnaAudioDriver();
#endif
                audioDriver.Play();

                // init engines
                engine = info.MetaEngine.Create(info, gfx, inputManager, audioDriver, saveFileManager);
                engine.ShowMenuDialogRequested += OnShowMenuDialogRequested;
                game.Services.AddService(engine);

                Task.Factory.StartNew(() =>
                {
                    UpdateGame();
                });
            }
        }
        /** Adds a single frame of sound data to the buffer */
        public void OutputSound(IAudioOutput audioOutput)
        {
            if (soundEnabled)
            {
                return;
            }

            int numChannels = 2;             // Always stereo for Game Boy
            int numSamples  = audioOutput.GetSamplesAvailable();

            byte[] b = new byte[numChannels * numSamples];

            if (channel1Enable)
            {
                channel1.Play(b, numSamples, numChannels);
            }
            if (channel2Enable)
            {
                channel2.Play(b, numSamples, numChannels);
            }
            if (channel3Enable)
            {
                channel3.Play(b, numSamples, numChannels);
            }
            if (channel4Enable)
            {
                channel4.Play(b, numSamples, numChannels);
            }

            audioOutput.Play(b);
        }
Esempio n. 6
0
            private void CalculateRatio(IAudioOutput input, double ratio, double refclk, double videoHz, double displayHz)
            {
                var format         = input.Format;
                var bytesPerSample = format.wBitsPerSample / 8;
                var length         = input.Sample.GetActualDataLength() / bytesPerSample;

                m_SampleIndex += length;

                if (m_SampleIndex < RATIO_ADJUST_INTERVAL)
                {
                    return;
                }

                m_SampleIndex = 0;

                // Fine tune further when we have refclk stats
                var actualVideoHz   = videoHz * (1 + refclk);
                var finalDifference = displayHz / actualVideoHz;
                // finalDifference will get smaller over time as refclk inches closer and closer to the target value
                var overshoot = m_Sanear ? SANEAR_OVERSHOOT : DIRECTSOUND_OVERSHOOT;
                var swing     = Math.Pow(finalDifference, overshoot);

                ratio *= Math.Max(1 - MAX_SWING, Math.Min(1 + MAX_SWING, swing));
                // Let it overshoot the final difference so we can converge faster
                // Sanear has a built-in low-pass filter that allows it to creep its sample rate towards the target
                // so we need a much higher overshoot to make it converge faster
                // DSound on the other hand doesn't

                m_Ratio = ratio;
            }
Esempio n. 7
0
    // Use this for initialization
    void Start()
    {
        // Init Keyboard mapping
        _keyMapping = new Dictionary <KeyCode, EmulatorBase.Button>();
        _keyMapping.Add(KeyCode.W, EmulatorBase.Button.Up);
        _keyMapping.Add(KeyCode.S, EmulatorBase.Button.Down);
        _keyMapping.Add(KeyCode.A, EmulatorBase.Button.Left);
        _keyMapping.Add(KeyCode.D, EmulatorBase.Button.Right);
        _keyMapping.Add(KeyCode.P, EmulatorBase.Button.A);
        _keyMapping.Add(KeyCode.O, EmulatorBase.Button.B);
        _keyMapping.Add(KeyCode.Return, EmulatorBase.Button.Start);
        _keyMapping.Add(KeyCode.Space, EmulatorBase.Button.Select);

        // Load emulator
        IVideoOutput drawable   = new DefaultVideoOutput();
        IAudioOutput audio      = GetComponent <DefaultAudioOutput>();
        ISaveMemory  saveMemory = new DefaultSaveMemory();

        Emulator = new Emulator(drawable, audio, saveMemory);
        ScreenRenderer.material.mainTexture = ((DefaultVideoOutput)Emulator.Video).Texture;

        gameObject.audio.enabled = false;
        StartCoroutine(LoadRom(Filename));

        // Disable some features to save on battery
        Input.gyro.enabled    = false;
        Input.compass.enabled = false;
    }
Esempio n. 8
0
 public void Render(IAudioOutput input, IAudioOutput output)
 {
     if (!Process(input, output))
     {
         AudioHelpers.CopySample(input.Sample, output.Sample, true);
     }
 }
Esempio n. 9
0
        public override void LoadContent()
        {
            if (!contentLoaded)
            {
                contentLoaded = true;
                spriteBatch = new SpriteBatch(ScreenManager.GraphicsDevice);

                font = ScreenManager.Content.Load<SpriteFont>("Fonts/MenuFont");
                inputManager = new XnaInputManager(ScreenManager.Game, info.Game);
                gfx = new XnaGraphicsManager(info.Game.Width, info.Game.Height, info.Game.PixelFormat, game.Window, ScreenManager.GraphicsDevice);
                ScreenManager.Game.Services.AddService<Core.Graphics.IGraphicsManager>(gfx);
                var saveFileManager = ServiceLocator.SaveFileManager;
#if WINDOWS_UWP
                audioDriver = new XAudio2Mixer();
#else
                audioDriver = new XnaAudioDriver();
#endif
                audioDriver.Play();

                // init engines
                engine = info.MetaEngine.Create(info, gfx, inputManager, audioDriver, saveFileManager);
                engine.ShowMenuDialogRequested += OnShowMenuDialogRequested;
                game.Services.AddService(engine);

                Task.Factory.StartNew(() =>
                {
                    UpdateGame();
                });
            }
        }
        void PlayCurrentSound(IAudioOutput[] outputs)
        {
            for (int i = 0; i < monoOutputs.Length; i++)
            {
                IAudioOutput output = outputs[i];
                if (output == null)
                {
                    output = GetPlatformOut();
                    output.Create(1, firstSoundOut);
                    if (firstSoundOut == null)
                    {
                        firstSoundOut = output;
                    }
                    outputs[i] = output;
                }
                if (!output.DoneRawAsync())
                {
                    continue;
                }

                try {
                    output.PlayRawAsync(chunk);
                } catch (InvalidOperationException ex) {
                    HandleSoundError(ex);
                }
                return;
            }
        }
Esempio n. 11
0
        void PlayCurrentSound(IAudioOutput[] outputs, float volume)
        {
            for (int i = 0; i < monoOutputs.Length; i++)
            {
                IAudioOutput output = outputs[i];
                if (output == null)
                {
                    output = MakeSoundOutput(outputs, i);
                }
                if (!output.DoneRawAsync())
                {
                    continue;
                }

                LastChunk l = output.Last;
                if (l.Channels == 0 || (l.Channels == chunk.Channels && l.BitsPerSample == chunk.BitsPerSample &&
                                        l.SampleRate == chunk.SampleRate))
                {
                    PlaySound(output, volume); return;
                }
            }

            // This time we try to play the sound on all possible devices,
            // even if it requires the expensive case of recreating a device
            for (int i = 0; i < monoOutputs.Length; i++)
            {
                IAudioOutput output = outputs[i];
                if (!output.DoneRawAsync())
                {
                    continue;
                }

                PlaySound(output, volume); return;
            }
        }
Esempio n. 12
0
		void PlaySound(IAudioOutput output, float volume) {
			try {
				output.Initalise(chunk);
				//uint newSrc = output.GetSource();
				//output.SetSource(newSrc);
				output.SetVolume(volume);
				
				/*LocalPlayer player = game.LocalPlayer;
				
				Vector3 camPos = game.CurrentCameraPos;
				Vector3 eyePos = game.LocalPlayer.EyePosition;
				Vector3 oneY = Vector3.UnitY;
				
				Vector3 lookPos;
				//lookPos.X = (float)(Math.Cos(player.HeadX) * Math.Sin(player.HeadY));
				//lookPos.Y = (float)(-Math.Sin(player.HeadX));
				//lookPos.Z = (float)(Math.Cos(player.HeadY) * Math.Cos(player.HeadX));
				lookPos.X = game.Graphics.View.Row1.X;
				lookPos.Y = game.Graphics.View.Row1.Y;
				lookPos.Z = game.Graphics.View.Row1.Z;
				lookPos = Vector3.Normalize(lookPos);
				
				Vector3 upPos;
				upPos.X = game.Graphics.View.Row2.X;
				upPos.Y = game.Graphics.View.Row2.Y;
				upPos.Z = game.Graphics.View.Row2.Z;
				upPos = Vector3.Normalize(upPos);*/
				
				Vector3 pos = game.LocalPlayer.EyePosition;
				Vector3 feetPos = game.LocalPlayer.Position;
				Vector3 vel = game.LocalPlayer.Velocity;
				float yaw = game.LocalPlayer.HeadY;
				output.SetSoundGain(0f);
				output.SetSoundRefDist(0.5f);
				output.SetSoundMaxDist(1000f);
				output.SetListenerPos(0, 0, 0);
				//output.SetListenerPos(pos.X, pos.Y, pos.Z);
				//output.SetListenerVel(vel.X, vel.Y, vel.Z);
				//output.SetListenerDir(yaw);
				//output.SetSoundPos(feetPos.X, feetPos.Y, feetPos.Z);
				if (!output.IsPosSet()) {
				//	output.SetSoundPos(feetPos.X, feetPos.Y, feetPos.Z);
				//	output.SetSoundVel(0, 0, 0);
				}
				output.SetSoundPos(0, 0, 0);
				//output.SetSoundRelative(true);
				
				output.PlayRawAsync(chunk);
			} catch (InvalidOperationException ex) {
				ErrorHandler.LogError("AudioPlayer.PlayCurrentSound()", ex);
				if (ex.Message == "No audio devices found")
					game.Chat.Add("&cNo audio devices found, disabling sounds.");
				else
					game.Chat.Add("&cAn error occured when trying to play sounds, disabling sounds.");
				
				SetSounds(0);
				game.SoundsVolume = 0;
			}
		}
Esempio n. 13
0
		void DisposeSound() {
			DisposeOutputs(ref monoOutputs);
			DisposeOutputs(ref stereoOutputs);
			if (firstSoundOut != null) {
				firstSoundOut.Dispose();
				firstSoundOut = null;
			}
		}
Esempio n. 14
0
		IAudioOutput MakeSoundOutput(IAudioOutput[] outputs, int i) {
			IAudioOutput output = GetPlatformOut();
			output.Create(1, firstSoundOut);
			if (firstSoundOut == null)
				firstSoundOut = output;
			
			outputs[i] = output;
			return output;
		}
Esempio n. 15
0
        public Emulator(IVideoOutput video = null, IAudioOutput audio = null, ISaveMemory saveMemory = null) : base(video, audio, saveMemory)
        {
            for (int i = 0; i < WIDTH * HEIGHT; i++)
            {
                SetPixel(i, 0xFF000000);
            }

            Video?.SetSize(WIDTH, HEIGHT);
        }
 void DisposeSound()
 {
     DisposeOutputs( ref monoOutputs );
     DisposeOutputs( ref stereoOutputs );
     if( firstSoundOut != null ) {
         firstSoundOut.Dispose();
         firstSoundOut = null;
     }
 }
Esempio n. 17
0
 void InitSound()
 {
     if (digBoard == null)
     {
         InitSoundboards();
     }
     monoOutputs   = new IAudioOutput[maxSounds];
     stereoOutputs = new IAudioOutput[maxSounds];
 }
Esempio n. 18
0
        public Emulator(IVideoOutput video, IAudioOutput audio = null, ISaveMemory saveMemory = null) : base(video, audio, saveMemory)
        {
            for (int i = 0; i < pixels.Length; i++)
            {
                pixels [i] = 0xFF000000;
            }

            Video.SetSize(WIDTH, HEIGHT);
        }
Esempio n. 19
0
        void DisposeOf( ref IAudioOutput output, ref Thread thread )
        {
            if( output == null ) return;
            output.Stop();
            thread.Join();

            output.Dispose();
            output = null;
            thread = null;
        }
Esempio n. 20
0
            private void PerformReclock(IAudioOutput output)
            {
                long start, end;

                output.Sample.GetTime(out start, out end);
                long endDelta = end - start;

                start = (long)(start * m_Ratio);
                output.Sample.SetTime(start, start + endDelta);
            }
Esempio n. 21
0
		// -------------------------------- EMU

		public Emulator(IVideoOutput video, IAudioOutput audio = null, ISaveMemory saveMemory = null) : base(video, audio, saveMemory)
		{
			pressButton.Instance.onClick += onClick;

			for (int i = 0; i < pixels.Length; i++)
			{
				pixels [i] = 0xFF000000;
			}

			Video.SetSize(WIDTH, HEIGHT);
		}
Esempio n. 22
0
    private void Awake()
    {
        // Init
        IVideoOutput drawable    = new DefaultVideoOutput();
        IAudioOutput audioOutput = audio;
        ISaveMemory  saveMemory  = new DefaultSaveMemory();

        Emulator = new Emulator(drawable, audioOutput, saveMemory);
        screenRenderer.material.mainTexture        = ((DefaultVideoOutput)Emulator.Video).Texture;
        audio.GetComponent <AudioSource>().enabled = false;
    }
Esempio n. 23
0
        Thread MakeThread(ThreadStart func, ref IAudioOutput output, string name)
        {
            output = GetPlatformOut();
            output.Create(10);

            Thread thread = new Thread(func);

            thread.Name         = name;
            thread.IsBackground = true;
            thread.Start();
            return(thread);
        }
Esempio n. 24
0
        public void Play(IAudioOutput audioOutput)
        {
            if (buffer == null)
            {
                loadTask.GetAwaiter().OnCompleted(Start);
            }
            else
            {
                Start();
            }

            void Start() => songPlayer.Start(audioOutput, buffer);
        }
Esempio n. 25
0
        void DisposeOf(ref IAudioOutput output, ref Thread thread)
        {
            if (output == null)
            {
                return;
            }
            output.Stop();
            thread.Join();

            output.Dispose();
            output = null;
            thread = null;
        }
Esempio n. 26
0
            public void Start(IAudioOutput audioOutput, byte[] data)
            {
                this.audioOutput = audioOutput ?? throw new ArgumentNullException(nameof(audioOutput));

                if (currentStream != data)
                {
                    Stop();
                    currentStream = data;
                    audioOutput.StreamData(data);
                }
                if (!audioOutput.Streaming)
                {
                    audioOutput.Start();
                }
            }
Esempio n. 27
0
            private bool CalculateRatio(IAudioOutput input)
            {
                if (!CompatibleAudioRenderer)
                {
                    return(false);
                }

                var stats = Player.Stats.Details;

                if (stats == null)
                {
                    return(false);
                }

                var videoInterval = Media.VideoInfo.AvgTimePerFrame;

                if (videoInterval < 1e-8)
                {
                    return(false); // audio only - no need to reclock
                }
                if (Math.Abs(stats.ActualSourceVideoIntervalUsec - videoInterval / 2) < 1000)
                {
                    videoInterval /= 2; // video is coming at twice the rate as reported (e.g. interlaced)
                }

                const int oneSecond = 1000000;
                var       videoHz   = oneSecond / videoInterval;
                var       displayHz = oneSecond / stats.DisplayRefreshIntervalUsec;
                var       ratio     = displayHz / videoHz;

                if (ratio > (100 + MAX_PERCENT_ADJUST) / 100 || ratio < (100 - MAX_PERCENT_ADJUST) / 100)
                {
                    m_SampleIndex = -8 * RATIO_ADJUST_INTERVAL;
                    return(true);
                }

                var refclk    = stats.RefClockDeviation;
                var hasRefClk = refclk > -10 && refclk < 10;

                if (!hasRefClk)
                {
                    m_SampleIndex = -8 * RATIO_ADJUST_INTERVAL;
                    return(true);
                }

                CalculateRatio(input, ratio, refclk, videoHz, displayHz);
                return(true);
            }
Esempio n. 28
0
            protected override bool Process(IAudioOutput input, IAudioOutput output)
            {
                if (!CalculateRatio(input))
                {
                    m_SampleIndex = -8 * RATIO_ADJUST_INTERVAL;
                    m_Ratio       = 1;
                    return(false);
                }

                // Passthrough from input to output
                AudioHelpers.CopySample(input.Sample, output.Sample, true);

                PerformReclock(output);

                return(true);
            }
Esempio n. 29
0
        public bool Play(IAudioOutput output)
        {
            switch (output)
            {
            case WasapiOutput wasapi:
                var outputSource = InitOutput(Synthesizer);
                wasapi.Source = outputSource;
                CurrentOutput = output;
                break;

            default:
                Initialized = false;
                return(false);
            }

            Initialized = true;
            return(true);
        }
Esempio n. 30
0
        void PlaySound(IAudioOutput output)
        {
            try {
                output.PlayRawAsync(chunk);
            } catch (InvalidOperationException ex) {
                ErrorHandler.LogError("AudioPlayer.PlayCurrentSound()", ex);
                if (ex.Message == "No audio devices found")
                {
                    game.Chat.Add("&cNo audio devices found, disabling sounds.");
                }
                else
                {
                    game.Chat.Add("&cAn error occured when trying to play sounds, disabling sounds.");
                }

                SetSound(false);
                game.UseSound = false;
            }
        }
Esempio n. 31
0
        private void btnPlay_Click(object sender, EventArgs e)
        {
            stream.Seek(0, SeekOrigin.Begin);
            decoder = new WaveDecoder(stream);

            if (trackBar1.Value < decoder.Frames)
            {
                decoder.Seek(trackBar1.Value);
            }
            trackBar1.Maximum = decoder.Samples;

            output = new AudioOutputDevice(this.Handle, decoder.SampleRate, decoder.Channels);
            output.NewFrameRequested   += new EventHandler <NewFrameRequestedEventArgs>(output_NewFrameRequested);
            output.Stopped             += new EventHandler(output_PlayingFinished);
            output.FramePlayingStarted += new EventHandler <PlayFrameEventArgs>(output_FramePlayingStarted);
            output.Play();

            updateButtons();
        }
        void DisposeOutputs( ref IAudioOutput[] outputs )
        {
            if( outputs == null ) return;
            bool soundPlaying = true;

            while( soundPlaying ) {
                soundPlaying = false;
                for( int i = 0; i < outputs.Length; i++ ) {
                    if( outputs[i] == null ) continue;
                    soundPlaying |= !outputs[i].DoneRawAsync();
                }
                if( soundPlaying )
                    Thread.Sleep( 1 );
            }

            for( int i = 0; i < outputs.Length; i++ ) {
                if( outputs[i] == null || outputs[i] == firstSoundOut ) continue;
                outputs[i].Dispose();
            }
            outputs = null;
        }
Esempio n. 33
0
        void PlaySound(IAudioOutput output, float volume)
        {
            try {
                output.SetVolume(volume);
                output.SetFormat(format);
                output.PlayData(0, chunk);
            } catch (InvalidOperationException ex) {
                ErrorHandler.LogError("AudioPlayer.PlayCurrentSound()", ex);
                if (ex.Message == "No audio devices found")
                {
                    game.Chat.Add("&cNo audio devices found, disabling sounds.");
                }
                else
                {
                    game.Chat.Add("&cAn error occured when trying to play sounds, disabling sounds.");
                }

                SetSounds(0);
                game.SoundsVolume = 0;
            }
        }
Esempio n. 34
0
        /** Adds a single frame of sound data to the buffer */
        public void OutputSound(IAudioOutput audioOutput)
        {
            if (soundEnabled)
                return;

            int numChannels = 2; // Always stereo for Game Boy
            int numSamples = audioOutput.GetSamplesAvailable();

            byte[] b = new byte[numChannels * numSamples];

            if (channel1Enable)
                channel1.Play(b, numSamples, numChannels);
            if (channel2Enable)
                channel2.Play(b, numSamples, numChannels);
            if (channel3Enable)
                channel3.Play(b, numSamples, numChannels);
            if (channel4Enable)
                channel4.Play(b, numSamples, numChannels);

            audioOutput.Play(b);
        }
Esempio n. 35
0
        private void init(IntPtr controlHandle, EventHandler<AudioOutputErrorEventArgs> AudioOutputError, EventHandler<PlayFrameEventArgs> FramePlayingStarted, EventHandler<NewFrameRequestedEventArgs> NewFrameRequested, EventHandler Stopped)
        {
            AudioDeviceCollection audioDevices = new AudioDeviceCollection(AudioDeviceCategory.Output);
            AudioDeviceInfo INfo = null;
            foreach (var item in audioDevices)
            {
                INfo = item;
            }
            // Here we can create the output audio device that will be playing the recording
            this.output = new AudioOutputDevice(INfo.Guid, controlHandle, decoder.SampleRate, decoder.Channels);

            // Wire up some events
            output.FramePlayingStarted += FramePlayingStarted;
            output.NewFrameRequested += NewFrameRequested;
            output.Stopped += Stopped;
            output.AudioOutputError += AudioOutputError;

            this.frames = this.decoder.Frames;
            this.samples = this.decoder.Samples;

            this.wholeSignal = getWholeSignal();
        }
Esempio n. 36
0
        void PlayCurrentSound(IAudioOutput[] outputs, float volume)
        {
            for (int i = 0; i < outputs.Length; i++)
            {
                IAudioOutput output = outputs[i];
                if (output == null)
                {
                    output     = MakeOutput(1);
                    outputs[i] = output;
                }
                else
                {
                    if (!output.IsFinished())
                    {
                        continue;
                    }
                }

                AudioFormat fmt = output.Format;
                if (fmt.Channels == 0 || fmt.Equals(format))
                {
                    PlaySound(output, volume); return;
                }
            }

            // This time we try to play the sound on all possible devices,
            // even if it requires the expensive case of recreating a device
            for (int i = 0; i < outputs.Length; i++)
            {
                IAudioOutput output = outputs[i];
                if (!output.IsFinished())
                {
                    continue;
                }

                PlaySound(output, volume); return;
            }
        }
Esempio n. 37
0
            protected sealed override bool Process(IAudioOutput input, IAudioOutput output)
            {
                if (input.Format.IsBitStreaming())
                {
                    return(false);
                }

                // WARNING: We assume input and output formats are the same

                // passthrough from input to output
                AudioHelpers.CopySample(input.Sample, output.Sample, false);

                IntPtr samples;

                input.Sample.GetPointer(out samples);
                var format         = input.Format;
                var bytesPerSample = format.wBitsPerSample / 8;
                var length         = input.Sample.GetActualDataLength() / bytesPerSample;
                var channels       = format.nChannels;
                var sampleFormat   = format.SampleFormat();

                return(Process(input, sampleFormat, samples, channels, length, output.Sample));
            }
Esempio n. 38
0
        private void btnPlay_Click(object sender, EventArgs e)
        {
            stream.Seek(0, SeekOrigin.Begin);
            decoder = new WaveDecoder(stream);

            if (trackBar1.Value < decoder.Frames)
                decoder.Seek(trackBar1.Value);
            trackBar1.Maximum = decoder.Samples;

            output = new AudioOutputDevice(this.Handle, decoder.SampleRate, decoder.Channels);

            output.FramePlayingStarted += output_FramePlayingStarted;
            output.NewFrameRequested += output_NewFrameRequested;
            output.Stopped += output_PlayingFinished;

            output.Play();

            updateButtons();
        }
Esempio n. 39
0
        public SkyEngine(GameSettings settings, IGraphicsManager gfxManager, IInputManager inputManager, IAudioOutput output, ISaveFileManager saveFileManager, bool debugMode = false)
        {
            _system = new SkySystem(gfxManager, inputManager, saveFileManager);

            _mixer = new Mixer(44100);
            // HACK:
            _mixer.Read(new byte[0], 0);
            output.SetSampleProvider(_mixer);

            var directory = ServiceLocator.FileStorage.GetDirectoryName(settings.Game.Path);
            _skyDisk = new Disk(directory);
            _skySound = new Sound(_mixer, _skyDisk, Mixer.MaxChannelVolume);

            SystemVars.Instance.GameVersion = _skyDisk.DetermineGameVersion();

            // TODO: music
            var dev = MidiDriver.DetectDevice(MusicDriverTypes.AdLib | MusicDriverTypes.Midi /*| MDT_PREFER_MT32*/, settings.AudioDevice);
            if (MidiDriver.GetMusicType(dev) == MusicType.AdLib)
            {
                SystemVars.Instance.SystemFlags |= SystemFlags.Sblaster;
                _skyMusic = new AdLibMusic(_mixer, _skyDisk);
            }
            else
            {
                SystemVars.Instance.SystemFlags |= SystemFlags.Roland;
                if ((MidiDriver.GetMusicType(dev) == MusicType.MT32)/* || ConfMan.getBool("native_mt32")*/)
                    _skyMusic = new Mt32Music((MidiDriver)MidiDriver.CreateMidi(_mixer, dev), _mixer, _skyDisk);
                else
                    _skyMusic = new GmMusic((MidiDriver)MidiDriver.CreateMidi(_mixer, dev), _mixer, _skyDisk);
            }

            if (IsCDVersion)
            {
                // TODO: configuration
                //if (ConfMan.hasKey("nosubtitles"))
                //{
                //    warning("Configuration key 'nosubtitles' is deprecated. Use 'subtitles' instead");
                //    if (!ConfMan.getBool("nosubtitles"))
                //        _systemVars.systemFlags |= SF_ALLOW_TEXT;
                //}

                //if (ConfMan.getBool("subtitles"))
                //    _systemVars.systemFlags |= SF_ALLOW_TEXT;

                //if (!ConfMan.getBool("speech_mute"))
                //    _systemVars.systemFlags |= SF_ALLOW_SPEECH;

            }
            else
                SystemVars.Instance.SystemFlags |= SystemFlags.AllowText;

            SystemVars.Instance.SystemFlags |= SystemFlags.PlayVocs;
            SystemVars.Instance.GameSpeed = 80;

            _skyCompact = new SkyCompact();
            _skyText = new Text(_skyDisk, _skyCompact);
            _skyMouse = new Mouse(_system, _skyDisk, _skyCompact);
            _skyScreen = new Screen(_system, _skyDisk, _skyCompact);

            InitVirgin();
            InitItemList();
            LoadFixedItems();
            _skyLogic = new Logic(_skyCompact, _skyScreen, _skyDisk, _skyText, _skyMusic, _skyMouse, _skySound);
            _skyMouse.Logic = _skyLogic;
            _skyScreen.Logic = _skyLogic;
            _skySound.Logic = _skyLogic;
            _skyText.Logic = _skyLogic;

            _skyControl = new Control(_skyScreen, _skyDisk, _skyMouse, _skyText, _skyMusic, _skyLogic, _skySound, _skyCompact, _system);
            _skyLogic.Control = _skyControl;

            // TODO: language

            // TODO: Setup mixer
            //SyncSoundSettings();

            // TODO: debugger
            //_debugger = new Debugger(_skyLogic, _skyMouse, _skyScreen, _skyCompact);
        }
        void PlayCurrentSound( IAudioOutput[] outputs )
        {
            for( int i = 0; i < monoOutputs.Length; i++ ) {
                IAudioOutput output = outputs[i];
                if( output == null ) {
                    output = GetPlatformOut();
                    output.Create( 1, firstSoundOut );
                    if( firstSoundOut == null )
                        firstSoundOut = output;
                    outputs[i] = output;
                }
                if( !output.DoneRawAsync() ) continue;

                try {
                    output.PlayRawAsync( chunk );
                } catch( InvalidOperationException ex ) {
                    HandleSoundError( ex );
                }
                return;
            }
        }
Esempio n. 41
0
        public SwordEngine(GameSettings settings, IGraphicsManager gfxManager, IInputManager inputManager,
            IAudioOutput output, ISaveFileManager saveFileManager, bool debugMode)
        {
            Settings = settings;
            GraphicsManager = gfxManager;
            _mixer = new Mixer(44100);
            // HACK:
            _mixer.Read(new byte[0], 0);
            output.SetSampleProvider(_mixer);
            System = new SwordSystem(gfxManager, inputManager, saveFileManager);

            var gameId = ((SwordGameDescriptor)settings.Game).GameId;
            _features = gameId == SwordGameId.Sword1Demo || gameId == SwordGameId.Sword1MacDemo ||
                        gameId == SwordGameId.Sword1PsxDemo
                ? 1U
                : 0;

            // TODO: debug
            // _console = new SwordConsole(this);

            SystemVars.Platform = settings.Game.Platform;

            // TODO:
            // CheckCdFiles();

            // TODO: debug(5, "Starting resource manager");
            var directory = ServiceLocator.FileStorage.GetDirectoryName(settings.Game.Path);
            var path = ServiceLocator.FileStorage.Combine(directory, "swordres.rif");
            _resMan = new ResMan(directory, path, SystemVars.Platform == Platform.Macintosh);
            // TODO: debug(5, "Starting object manager");

            _objectMan = new ObjectMan(_resMan);
            _mouse = new Mouse(System, _resMan, _objectMan);
            _screen = new Screen(directory, System, _resMan, _objectMan);
            _music = new Music(Mixer, directory);
            _sound = new Sound(settings, _mixer, _resMan);
            _menu = new Menu(_screen, _mouse);
            _logic = new Logic(this, _objectMan, _resMan, _screen, _mouse, _sound, _music, _menu, Mixer);
            _mouse.UseLogicAndMenu(_logic, _menu);

            // TODO:
            //SyncSoundSettings();

            SystemVars.JustRestoredGame = 0;
            SystemVars.CurrentCd = 0;
            SystemVars.ControlPanelMode = ControlPanelMode.CP_NEWGAME;
            SystemVars.ForceRestart = false;
            SystemVars.WantFade = true;
            //_systemVars.realLanguage = Common::parseLanguage(ConfMan.get("language"));
            SystemVars.RealLanguage = new CultureInfo("en-GB");

            //switch (SystemVars.RealLanguage.TwoLetterISOLanguageName)
            //{
            //    case "de":
            //        SystemVars.Language = Language.BS1_GERMAN;
            //        break;
            //    case "fr":
            //        SystemVars.Language = Language.BS1_FRENCH;
            //        break;
            //    case "it":
            //        SystemVars.Language = Language.BS1_ITALIAN;
            //        break;
            //    case "es":
            //        SystemVars.Language = Language.BS1_SPANISH;
            //        break;
            //    case "pt":
            //        SystemVars.Language = Language.BS1_PORT;
            //        break;
            //    case "cz":
            //        SystemVars.Language = Language.BS1_CZECH;
            //        break;
            //    default:
            //        SystemVars.Language = Language.BS1_ENGLISH;
            //        break;
            //}

            // TODO:
            //_systemVars.showText = ConfMan.getBool("subtitles");

            SystemVars.PlaySpeech = 1;
            _mouseState = 0;

            // Some Mac versions use big endian for the speech files but not all of them.
            if (SystemVars.Platform == Platform.Macintosh)
                _sound.CheckSpeechFileEndianness();

            _logic.Initialize();
            _objectMan.Initialize();
            _mouse.Initialize();
            _control = new Control(saveFileManager, _resMan, _objectMan, System, _mouse, _sound, _music);
        }
Esempio n. 42
0
		public EmulatorBase(IVideoOutput video, IAudioOutput audio = null, ISaveMemory saveMemory = null)
		{
			Video = video;
			Audio = audio;
			SaveMemory = saveMemory;
		}
 void InitSound()
 {
     if( digBoard == null ) InitSoundboards();
     monoOutputs = new IAudioOutput[maxSounds];
     stereoOutputs = new IAudioOutput[maxSounds];
 }
Esempio n. 44
0
 public IEngine Create(GameSettings settings, IGraphicsManager gfxManager, IInputManager inputManager, IAudioOutput output, ISaveFileManager saveFileManager, bool debugMode = false)
 {
     return ScummEngine.Create(settings, gfxManager, inputManager, output, debugMode);
 }
Esempio n. 45
0
        Thread MakeThread( ThreadStart func, ref IAudioOutput output, string name )
        {
            output = GetPlatformOut();
            output.Create( 5 );

            Thread thread = new Thread( func );
            thread.Name = name;
            thread.IsBackground = true;
            thread.Start();
            return thread;
        }
Esempio n. 46
0
        public static ScummEngine Create(GameSettings settings, IGraphicsManager gfxManager, IInputManager inputManager, IAudioOutput output, bool debugMode = false)
        {
            ScummEngine engine = null;
            var game = (GameInfo)settings.Game;
            var mixer = new Mixer(44100);
            output.SetSampleProvider(mixer);

            if (game.Version == 0)
            {
                engine = new ScummEngine0(settings, gfxManager, inputManager, mixer);
            }
            else if ((game.Version == 1) || (game.Version == 2))
            {
                engine = new ScummEngine2(settings, gfxManager, inputManager, mixer);
            }
            else if (game.Version == 3)
            {
                engine = new ScummEngine3(settings, gfxManager, inputManager, mixer);
            }
            else if (game.Version == 4)
            {
                engine = new ScummEngine4(settings, gfxManager, inputManager, mixer);
            }
            else if (game.Version == 5)
            {
                engine = new ScummEngine5(settings, gfxManager, inputManager, mixer);
            }
            else if (game.Version == 6)
            {
                engine = new ScummEngine6(settings, gfxManager, inputManager, mixer);
            }
            else if (game.Version == 7)
            {
                engine = new ScummEngine7(settings, gfxManager, inputManager, mixer);
            }
            else if (game.Version == 8)
            {
                engine = new ScummEngine8(settings, gfxManager, inputManager, mixer);
            }
            Instance = engine;
            engine.DebugMode = debugMode;
            engine.InitOpCodes();
            engine.SetupVars();
            engine.ResetScummVars();
            return engine;
        }
Esempio n. 47
0
        /// <summary>
        ///   Plays the recorded audio stream.
        /// </summary>
        /// 
        private void btnPlay_Click(object sender, EventArgs e)
        {
            // First, we rewind the stream
            stream.Seek(0, SeekOrigin.Begin);

            // Then we create a decoder for it
            decoder = new WaveDecoder(stream);

            // Configure the track bar so the cursor
            // can show the proper current position
            if (trackBar1.Value < decoder.Frames)
                decoder.Seek(trackBar1.Value);
            trackBar1.Maximum = decoder.Samples;

            // Here we can create the output audio device that will be playing the recording
            output = new AudioOutputDevice(this.Handle, decoder.SampleRate, decoder.Channels);

            // Wire up some events
            output.FramePlayingStarted += output_FramePlayingStarted;
            output.NewFrameRequested += output_NewFrameRequested;
            output.Stopped += output_PlayingFinished;

            // Start playing!
            output.Play();

            updateButtons();
        }