Exemplo n.º 1
0
        } // loading jingle

        private void GetRawData(FMOD.Sound tempSound, int channels, int bits, uint pcm)
        {
            tempSound.CheckNull("tempSound");
            uint   len1 = 0, len2 = 0;
            IntPtr ptr1 = IntPtr.Zero, ptr2 = IntPtr.Zero;

            switch (bits)
            {
            case 16:
            {
                FMOD.RESULT result = tempSound.@lock(0, (uint)(pcm * channels * sizeof(short)), ref ptr1, ref ptr2, ref len1, ref len2);
                ErrorCheck(result);

                SoundDataBuffer = new CircularBuffer((int)(pcm * channels));
                Marshal.Copy(ptr1, SoundDataBuffer.Buffer, 0, (int)(len1 / sizeof(short)));
                if (len2 > 0)
                {
                    Marshal.Copy(ptr2, SoundDataBuffer.Buffer, (int)(len1 / sizeof(short)), (int)(len2 / sizeof(short)));
                }

                tempSound.unlock(ptr1, ptr2, len1, len2);
                break;
            }

            default:
                throw new InvalidOperationException("Bits count unsupported");
            }
        }
Exemplo n.º 2
0
        public static FMOD.RESULT createSound(this FMOD.System system, IntPtr data, FMOD.MODE mode, ref FMOD.CREATESOUNDEXINFO exinfo, ref FMOD.Sound sound)
        {
            FMOD.RESULT result   = FMOD.RESULT.OK;
            IntPtr      soundraw = new IntPtr();

            FMOD.Sound soundnew = null;

            try
            {
                result = FMOD_System_CreateSound(system.getRaw(), data, mode, ref exinfo, ref soundraw);
            }
            catch
            {
                result = FMOD.RESULT.ERR_INVALID_PARAM;
            }
            if (result != FMOD.RESULT.OK)
            {
                return(result);
            }

            if (sound == null)
            {
                soundnew = new FMOD.Sound();
                soundnew.setRaw(soundraw);
                sound = soundnew;
            }
            else
            {
                sound.setRaw(soundraw);
            }

            return(result);
        }
Exemplo n.º 3
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            if (sound != null)
            {
                if (channel != null)
                {
                    channel.stop();
                    channel = null;
                }
                sound.release();
                sound = null;
            }

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                FMOD.RESULT result;

                result = system.createStream(dialog.FileName, FMOD.MODE.SOFTWARE | FMOD.MODE._2D, ref sound);
                ERRCHECK(result);

                textBox.Text = dialog.FileName;
            }

            playButton.Text = "Play";
        }
Exemplo n.º 4
0
 internal void OnChannelCleared(SoundChannel_FMOD chnl)
 {
     FMOD.Sound snd = chnl.RefFMODSound;
     if (snd != null)
     {
         Sounds.Remove(snd);
         snd.release();
         //bool invalid = true;
         //if (dcSounds.ContainsValue(snd))
         //{
         //    foreach (SoundChannel_FMOD ch in m_aChannels)
         //    {
         //        if (ch != chnl && ch.RefFMODSound == snd)
         //        {
         //            invalid = false;
         //            break;
         //        }
         //    }
         //}
         //if (invalid)
         //{
         //    if (dcSounds.ContainsValue(snd))
         //    {
         //        string[] files = (from kv in dcSounds where kv.Value == snd select kv.Key).ToArray();
         //        if (files != null)
         //        {
         //            foreach (var file in files)
         //                dcSounds.Remove(file);
         //        }
         //    }
         //    snd.release();
         //}
         chnl.RefFMODSound = null;
     }
 }
        public void Play(string audioPath, bool loop = false, int loopCount = -1)
        {
            if (!Game.dummyAudioOn)
            {
                return;
            }

            Stop();

            FMOD.Sound sound = _audioMaster.LoadSound(audioPath);

            if (loop)
            {
                sound.setMode(FMOD.MODE.LOOP_NORMAL);
                sound.setLoopCount(loopCount - 1);
            }
            else
            {
                sound.setMode(FMOD.MODE.LOOP_OFF);
            }

            FMOD.RESULT result;

            result = _audioMaster.GetFmodSystem().playSound(sound, null, true, out _channel); // 3rd parameter : paused
            if (result != FMOD.RESULT.OK)
            {
                Console.WriteLine("[SpeakerComponent Play] FMOD playSound failed : " + result);
            }

            UpdateSpeakerAttributes();
            setVolume(100.0f);
            PauseResume();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Stop and try to release FMOD sound resources
        /// </summary>
        void Stop_Internal()
        {
            this.GetComponent <AudioSource>().Stop();

            this.isRecording = false;
            this.isPaused    = false;

            /*
             *  Shut down sound
             */
            if (sound != null)
            {
                result = sound.release();
                ERRCHECK(result, "sound.release", false);
            }

            sound = null;

            /*
             * Shut down
             */
            if (system != null)
            {
                result = system.close();
                ERRCHECK(result, "system.close", false);

                result = system.release();
                ERRCHECK(result, "system.release", false);
            }

            system = null;
        }
Exemplo n.º 7
0
        public void UpdateSound(string name, ref FMOD.Sound s, Boolean Loop)
        {
            FMOD.RESULT result;
            string      strNameSpace =
                System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();

            Stream str = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(strNameSpace + ".Sounds." + name);

            //Block = new Bitmap(str);
            byte[] Arr = new byte[str.Length];
            str.Read(Arr, 0, (int)str.Length);
            FMOD.CREATESOUNDEXINFO inf = new FMOD.CREATESOUNDEXINFO();
            inf.cbsize = Marshal.SizeOf(inf);
            inf.length = (uint)str.Length;

            result = soundsystem.createSound(Arr, FMOD.MODE.SOFTWARE | FMOD.MODE.OPENMEMORY | FMOD.MODE._3D, ref inf, ref s);
            ERRCHECK(result);

            if (!Loop)
            {
                s.setMode(FMOD.MODE.LOOP_OFF);
            }
            else
            {
                s.setMode(FMOD.MODE.LOOP_NORMAL);
            }

            ERRCHECK(result);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Frees channel, sound and DSP resources
        /// </summary>
        private void FreeChannelResources()
        {
            //stop any playing channels
            if (_channel != null)
            {
                _channel.stop();
                _channel = null;
            }

            //release sound
            if (_sound != null)
            {
                _sound.release();
                _sound = null;
            }

            //free waveform DSP
            if (_dsp != null)
            {
                _dsp.release();
                _dsp = null;
            }

            //destroy the equalizer
            DestroyEqualizer();
        }
Exemplo n.º 9
0
        public SoundSystem()
        {
            var ret = FMOD.Result.OK;

            system = null;
            Program.WriteLine("SoundSystem: _ctor");
            if (!IniFile.GetValue("audio", "enabled", true))
            {
                return;
            }
            musicVolume = IniFile.GetValue("audio", "musicvolume", 100) / 100f;
            soundVolume = IniFile.GetValue("audio", "soundvolume", 100) / 100f;

            Program.Write("SoundSystem: trying to create FMOD system...");
            try
            {
                FMOD.Factory.CreateSystem(ref system);
            }
            catch (DllNotFoundException)
            {
                Program.WriteLine(" Library not found. Disabling sound.");
                return;
            }
            Program.WriteLine(" " + ret.ToString());
            if (ret != FMOD.Result.OK)
            {
                return;
            }
            Program.Write("SoundSystem: system.init...");
            ret = system.Initialize(8, FMOD.InitFlags.Normal, IntPtr.Zero);
            Program.WriteLine(" " + ret.ToString());
            if (ret != FMOD.Result.OK)
            {
                system = null;
                return;
            }
            music        = null;
            musicChannel = null;

            sounds = new Dictionary <string, Sound>();

            Program.WriteLine("SoundSystem: loading libraries...");
            musicLibrary = Mix.GetTokenTree("music.tml");
            soundLibrary = Mix.GetTokenTree("sound.tml");

            Program.WriteLine("SoundSystem: _ctor DONE");
            Program.WriteLine("Null report:");
            if (system == null)
            {
                Program.WriteLine(" * system");
            }
            if (music == null)
            {
                Program.WriteLine(" * music");
            }
            if (musicChannel == null)
            {
                Program.WriteLine(" * musicChannel");
            }
        }
Exemplo n.º 10
0
        private MusicPlayer()
        {
            result = FMOD.Factory.System_Create(out FMODSystem);

            if (result != FMOD.RESULT.OK)
            {
                throw new Exception("This crap didn't work!!");
            }

            result = FMODSystem.setDSPBufferSize(1024, 10);
            result = FMODSystem.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)0);

            var info = new FMOD.CREATESOUNDEXINFO();
            var song = new FMOD.Sound();

            ChannelGroup = new FMOD.ChannelGroup();
            ChannelGroup.clearHandle();

            result = FMODSystem.createStream("rain.ogg", FMOD.MODE.DEFAULT, out song);

            result = FMODSystem.playSound(song, ChannelGroup, false, out Channel);



            bool isPlaying = false;

            Channel.isPlaying(out isPlaying);

            Channel.setVolume(1);
            Channel.setMode(FMOD.MODE.LOOP_NORMAL);
            Channel.setLoopCount(-1);

            int t = 1;
        }
        private static FMOD.RESULT FMOD_EVENT_CALLBACK(IntPtr eventraw, FMOD.EVENT_CALLBACKTYPE type, IntPtr param1, IntPtr param2, IntPtr userdata)
        {
            unsafe
            {
                switch (type)
                {
                case FMOD.EVENT_CALLBACKTYPE.SOUNDDEF_CREATE:
                {
                    int   entryindex  = *(int *)param2.ToPointer();        // [in]  (int) index of sound definition entry
                    uint *realpointer = (uint *)param2.ToPointer();        // [out] (FMOD::Sound *) a valid lower level API FMOD Sound handle

                    FMOD.Sound s = null;
                    fsb.getSubSound(entryindex, ref s);

                    *realpointer = (uint)s.getRaw().ToPointer();

                    break;
                }

                case FMOD.EVENT_CALLBACKTYPE.SOUNDDEF_RELEASE:
                {
                    break;
                }
                }
            }
            return(FMOD.RESULT.OK);
        }
Exemplo n.º 12
0
        public Sound(SoundData _data)
        {
            data = _data;
#if !NO_FMOD
            mSound = null;
#endif
        }
Exemplo n.º 13
0
 private void FMODrelease()
 {
     if (channel != null)
     {
         FMOD.Sound  currentSound;
         FMOD.RESULT result = channel.getCurrentSound(out currentSound);
         if (result != FMOD.RESULT.ERR_CHANNEL_STOLEN)
         {
             ERRCHECK(result, "channel.getCurrentSound", false);
             if (currentSound == sound || currentSound == subSound)
             {
                 result = channel.stop();
                 if (result != FMOD.RESULT.ERR_CHANNEL_STOLEN)
                 {
                     ERRCHECK(result, "channel.stop", false);
                 }
             }
         }
         channel = null;
     }
     if (subSound != null)
     {
         FMOD.RESULT result = subSound.release();
         ERRCHECK(result, "subSound.release", false);
         subSound = null;
     }
     if (sound != null)
     {
         FMOD.RESULT result = sound.release();
         ERRCHECK(result, "sound.release", false);
         sound = null;
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Attempts to stop playback on this channel, and release it
        /// </summary>
        public void StopAndRelease()
        {
            lock (this.p_Lock)
            {
                if (!this.isDisposed)
                {
                    this.isDisposed = true;
                    FMOD.Sound currentSound = null;

                    FMOD.RESULT result = this.Channel.getCurrentSound(ref currentSound);
                    if (result != FMOD.RESULT.OK)
                    {
                        throw new FMODException("Unable to retrieve current sound from channel", result);
                    }

                    result = currentSound.release();
                    if (result != FMOD.RESULT.OK)
                    {
                        throw new FMODException("Unable to release sound", result);
                    }
                    result = this.Channel.stop();
                    if (result != FMOD.RESULT.OK && result != FMOD.RESULT.ERR_INVALID_HANDLE) // FMOD.RESULT.ERR_INVALID_HANDLE usually means that the channel hasn't even started playing yet
                    {
                        throw new FMODException("Unable to release channel", result);
                    }
                    this.system.RemoveContainer(this);
                }
            }
        }
Exemplo n.º 15
0
        int AddSample(FMOD.Sound sound, string name)
        {
            if (samples.Contains(sound))
            {
                return(samples.IndexOf(sound));
            }

            // Get properties
            sound.getLength(out uint length, FMOD.TIMEUNIT.PCMBYTES);
            sound.getLoopPoints(out uint loop_start, FMOD.TIMEUNIT.PCMBYTES, out uint loop_end, FMOD.TIMEUNIT.PCMBYTES);
            sound.getLoopCount(out int loopCount);
            sound.getDefaults(out float frequency, out int priority);

            // Get sample data
            sound.@lock(0, length, out IntPtr snd, out IntPtr idc, out uint len, out uint idc2);
            var pcm8 = new byte[len];

            Marshal.Copy(snd, pcm8, 0, (int)len);
            sound.unlock(snd, idc, len, idc2);
            short[] pcm16 = pcm8.Select(i => (short)(i << 8)).ToArray();

            // Add to file
            sf2.AddSample(pcm16, name, loopCount == -1, loop_start, (uint)frequency, 60, 0);
            samples.Add(sound);
            return(samples.Count - 1);
        }
Exemplo n.º 16
0
 /// <summary>
 /// Initializes a new <see cref="FMODChannel"/> and sets it's values to the ones specified
 /// </summary>
 /// <param name="channel">The FMOD.Channel to wrap around</param>
 /// <param name="sound">The FMOD.Sound to wrap</param>
 /// <param name="context">The SynchronizationContext to use for callbacks</param>
 /// <param name="id">the ID of this container</param>
 /// <param name="system">The <see cref="FMODSystem"/> that contains this channel</param>
 internal FMODChannel(FMODSystem system, FMOD.Channel channel, FMOD.Sound sound, Guid id)
 {
     this.system  = system;
     this.id      = id;
     this.Channel = channel;
     this.sound   = sound;
 }
Exemplo n.º 17
0
        void StopFMODSound()
        {
            if (channel != null)
            {
                result = channel.stop();
                // ERRCHECK(result, "channel.stop", false);
            }

            channel = null;

            System.Threading.Thread.Sleep(50);

            if (sound != null)
            {
                result = sound.release();
                // ERRCHECK(result, "sound.release", false);
            }

            sound = null;

            if (this.pcmReadCallbackBuffer != null)
            {
                this.pcmReadCallbackBuffer[0].Clear();
                this.pcmReadCallbackBuffer[1].Clear();
            }
        }
Exemplo n.º 18
0
        public SoundSource(FMOD.System system, FMOD.Sound sound, int posx, int posy)
        {
            FMOD.RESULT result;

            mPos.x = posx;
            mPos.y = posy;
            mPos.z = 0;

            mVel.x = 0;
            mVel.y = 0;
            mVel.z = 0;

            mSystem = system;

            result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, true, ref mChannel);
            VirtualVoices.ERRCHECK(result);

            SetPosition(mPos.x, mPos.y);

            Random r = new Random(posx);

            result = mChannel.setFrequency(r.Next(22050, 44100));
            VirtualVoices.ERRCHECK(result);

            result = mChannel.setPaused(false);
            VirtualVoices.ERRCHECK(result);

            mBrushBlue = new SolidBrush(Color.Blue);
            mBrushRed  = new SolidBrush(Color.Red);
        }
Exemplo n.º 19
0
        public SoundSystem()
        {
            var ret = FMOD.Result.OK;

            system = null;

            try
            {
                FMOD.Factory.CreateSystem(ref system);
            }
            catch (DllNotFoundException)
            {
                return;
            }
            if (ret != FMOD.Result.OK)
            {
                return;
            }
            ret = system.Initialize(8, FMOD.InitFlags.Normal, IntPtr.Zero);
            if (ret != FMOD.Result.OK)
            {
                system = null;
                return;
            }
            sounds       = new Dictionary <string, Sound>();
            music        = null;
            musicChannel = null;
        }
Exemplo n.º 20
0
        private void LoadMidi()
        {
            FMOD.RESULT result;

            sounds[1] = new FMOD.Sound();
            result    = system.createSound("dune_win_01.MID", FMOD.MODE.SOFTWARE | FMOD.MODE.CREATESTREAM, ref sounds[1]);
            ERRCHECK(result);
        }
Exemplo n.º 21
0
 public void Dispose()
 {
     if (sounds != null)
     {
         sounds.release();
         sounds = null;
     }
 }
Exemplo n.º 22
0
        private void LoadSounds()
        {
            FMOD.RESULT result;

            sounds[0] = new FMOD.Sound();
            result    = system.createSound("FancyPants.wav", FMOD.MODE.HARDWARE, ref sounds[0]);
            ERRCHECK(result);
        }
Exemplo n.º 23
0
        public void LoadSound_LoadSuccessTest()
        {
            FMOD.Sound snd      = null;
            bool       bSuccess = s_system.LoadSound("TestResources/pumpuplooped.wav", true, out snd);

            Assert.IsTrue(bSuccess);
            Assert.IsNotNull(snd);
        }
Exemplo n.º 24
0
        public SoundSource GetSoundSource(string name, bool ambient, bool local)
        {
            lock (this)
            {
                FMOD.Sound sound = GetSound(name, ambient, local);

                return(new SoundSource(fmod, sound, name, ambient));
            }
        }
Exemplo n.º 25
0
        private void JingleInit(string filename)
        {
            FMOD.Sound tempSound = null;
            thisLock = new Object();
            // Retrieve information about sound
            FMOD.RESULT result = system.createSound(filename, (FMOD.MODE._2D | FMOD.MODE.SOFTWARE), ref tempSound);
            ErrorCheck(result);

            FMOD.SOUND_TYPE   soundType   = (FMOD.SOUND_TYPE) 0;
            FMOD.SOUND_FORMAT soundFormat = (FMOD.SOUND_FORMAT) 0;

            int tempBits     = 0,
                tempChannels = 0,
                tempPriority = 0;

            uint tempPcm = 0;

            float tempFrequency = 0.0f,
                  tempPan       = 0.0f,
                  tempVolume    = 0.0f;

            result = tempSound.getFormat(ref soundType, ref soundFormat, ref tempChannels, ref tempBits);
            ErrorCheck(result);

            result = tempSound.getDefaults(ref tempFrequency, ref tempVolume, ref tempPan, ref tempPriority);
            ErrorCheck(result);

            result = tempSound.getLength(ref tempPcm, FMOD.TIMEUNIT.PCM);
            ErrorCheck(result);

            // Fill sound parameters
            ChannelCount = tempChannels;
            Frequency    = (int)tempFrequency;
            pcm          = tempPcm;
            bits         = tempBits;

            // Obtain Raw PCM data from sound
            GetRawData(tempSound, tempChannels, tempBits, tempPcm);


            // Release temp sound instance
            tempSound.release();
            tempSound = null;


            FMOD.CREATESOUNDEXINFO exInfo = new FMOD.CREATESOUNDEXINFO();
            exInfo.cbsize           = Marshal.SizeOf(exInfo);
            exInfo.length           = (uint)(pcm * sizeof(short));
            exInfo.numchannels      = ChannelCount;
            exInfo.format           = FMOD.SOUND_FORMAT.PCM16;
            exInfo.defaultfrequency = (int)Frequency;
            // Create a stream from obtained data

            result = system.createStream(SoundDataBuffer.Buffer, (FMOD.MODE.OPENMEMORY | FMOD.MODE.OPENRAW), ref exInfo, ref sounds);
            ErrorCheck(result);
        } // loading jingle
Exemplo n.º 26
0
        public void Uninitialize()
        {
            if (cdSound != null)
            {
                cdSound.release();
                cdSound = null;
            }

            Stop();
        }
Exemplo n.º 27
0
        /// <summary>
        /// Load and play a sound at a given location.
        /// </summary>
        /// <param name="p_filename">Path to a supported sound file.</param>
        /// <param name="p_bLooped">Whether or not to loop playback.</param>
        /// <returns></returns>
        public bool LoadSound(string p_filename, bool p_bLooped, out FMOD.Sound o_sound)
        {
            FMOD.RESULT r = m_fmodSystem.createSound(
                p_filename,
                p_bLooped? FMOD.MODE.LOOP_NORMAL : FMOD.MODE.LOOP_OFF,
                out o_sound
                );

            return(r == FMOD.RESULT.OK);
        }
Exemplo n.º 28
0
 public static void Stop()
 {
     if (SoundEngine.IsPlaying())
     {
         FMODChannel.stop();
         FMODSound.release();
         FMODChannel = null;
         FMODSound   = null;
     }
 }
Exemplo n.º 29
0
 private FMOD.Channel PlaySound(FMOD.Sound sound, bool play)
 {
     FMOD.Channel channel = null;
     FMOD.RESULT  result  = this.system.playSound(FMOD.CHANNELINDEX.FREE, sound, !play, ref channel);
     if (result != FMOD.RESULT.OK)
     {
         throw new FMODException("Unable to play sound", result);
     }
     return(channel);
 }
Exemplo n.º 30
0
        // every level transition we dump all fmod data in an attempt to eliminate the silly bugs
        public void releaseSound()
        {
            if (mSound != null)
            {
                FMOD.RESULT result = mSound.release();
                ERRCHECK(result);
            }

            mSound = null;
        }
Exemplo n.º 31
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            if (sound != null)
            {
                if (channel != null)
                {
                    channel.stop();
                    channel = null;
                }
                sound.release();
                sound = null;
            }

            if(dialog.ShowDialog() == DialogResult.OK)
            {
                FMOD.RESULT result;

                result = system.createStream(dialog.FileName, FMOD.MODE.SOFTWARE | FMOD.MODE._2D, ref sound);
                ERRCHECK(result);

                textBox.Text = dialog.FileName;
            }

            playButton.Text = "Play";
        }
Exemplo n.º 32
0
        private void ResetEverything()
        {
            // Stopping Music
            if(fmodChannel != null)
                fmodChannel.stop();

            fmodSystem = null;
            fmodChannel = null;
            theSong = null;
            szSongName = "";
            nCurrentPositionMS = 0;
            nLengthMS = 0;
            bPlaying = false;
            bIsFastforwarding = false;
            bIsRewinding = false;
            bPaused = false;
            //bFreq = false;
            bRunning = true;
            bListChanged = false;

            listBeats = new List<Beat>();

            MouseAddBeat = new Beat();
            szClickedEventEdit = "";

            nMouseScroll = 0;

            MouseSelectStartPoint = new Point();

            MouseSelectRect = Rectangle.Empty;

            SelectedBeats.Clear();
            CopiedBeats.Clear();

            TimeCurrentLabel.Text = "0(s)";
            TimeLengthLabel.Text = "0(s)";
            BeatCountLabel.Text = "0";
            BPMCurrentLabel.Text = "0";

            // Clean shit up RIGHT NAO!!!
            GC.Collect();
        }
Exemplo n.º 33
0
        public Sound(SoundData _data)
        {
            data = _data;
#if !NO_FMOD
            mSound = null;
#endif
        }
Exemplo n.º 34
0
        public void Play()
        {
#if !NO_FMOD
            if (Playing && mChannel != null)
            {
                bool paused = false;
                mChannel.getPaused(ref paused);
                if (paused)
                {
                    mChannel.setPaused(false);
                    return;
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
            else
            {
                if (data._streamIndex >= 0)
                {
                    if (mStreamBytes != null)
                    {
                        mAbortStream = false;
                        return;
                    }
                    // if this isn't true, we may have 2 async requests to play, which would be super bad
                    GSGE.Debug.assert(mStreamBytes == null);
                    GSGE.Debug.assert(mAbortStream == false);
                }
                if (mSound != null)
                    Dispose();

                FMOD.RESULT result;
                FMOD.CREATESOUNDEXINFO exinfo = SoundData.exinfo;
                exinfo.cbsize = Marshal.SizeOf(exinfo);

                // allocate streaming?
                if (data._size > 0)
                {
                    mStreamRequested = true;
                    mStreamBytes = new byte[data._size];

                    string file = "Content/Audio/";
                    if (data._persist)
                        file += "Deferred/";
                    else
                        file += "Streaming/";
                    file += data._streamIndex;
                    file += ".mp3";


                    //GSGE.Debug.logMessage("streaming audio " + file);
                    NaCl.AsyncFS.FileStream fs = new NaCl.AsyncFS.FileStream(file, System.IO.FileMode.Open);

                    fs.BeginRead(mStreamBytes,
                        0,
                        mStreamBytes.Length,
                        delegate(IAsyncResult aresult)
                        {
                            int bytesRead;
                            try
                            {
                                bytesRead = fs.EndRead(aresult);
                            }
                            catch (System.IO.FileNotFoundException)
                            {
                                bytesRead = -1;
                            }
                            fs.Close();

                            if (bytesRead != data._size)
                            {
                                GSGE.Debug.logMessage("Error streaming in sound " + data._streamIndex);
                                mStreamStarted = true;
                                Dispose();
                                return;
                            }

                            if (data._persist)
                            {
                                byte[] audiodata = mStreamBytes;

                                mStreamBytes = null;
                                mStreamRequested = false;
                                mStreamStarted = false;

                                // reconfigure parent Sound to be persistent now.
                                data.setPersistent(audiodata);

                                if (mAbortStream)
                                {
                                    Dispose();
                                }
                                else
                                {
                                    Play();
                                }
                            }
                            else
                            {
                                mStreamStarted = true;
                                if (mAbortStream)
                                {
                                    Dispose();
                                }
                                else
                                {
                                    exinfo.length = (uint)mStreamBytes.Length;
                                    FMOD.MODE mode = FMOD.MODE.OPENMEMORY_POINT | FMOD.MODE.CREATECOMPRESSEDSAMPLE | FMOD.MODE.SOFTWARE;
                                    if (data._looping)
                                        mode |= FMOD.MODE.LOOP_NORMAL;
                                    result = FMOD.Framework.system.createSound(mStreamBytes, mode, ref exinfo, ref mSound);
                                    mOwnSound = true;
                                    ERRCHECK(result);

                                    AudioEngine audioengine = GSGE.AudioManager.GetAudioManager().GetAudioEngine();
                                    audioengine.FmodSounds.Add(this);

                                    result = FMOD.Framework.system.playSound(FMOD.CHANNELINDEX.FREE, mSound, false, ref mChannel);
                                    if (mSound == null)
                                    {
                                        Dispose();
                                    }
                                    else
                                    {
                                        GSGE.Debug.assert(mSound != null);
                                        ERRCHECK(result);
                                        mChannel.getFrequency(ref mBaseFrequency);
                                    }
                                }
                            }

                            // all streaming sounds need to assign these asap
                            Volume = _volume;
                            Pitch = _pitch;
                            LowPassCutoff = _lowPassCutoff;
                            Reverb = _reverb;

                            mAbortStream = false;
                        }, null);
                }
                else
                {
                    if (data.mSound == null)
                    {
                        data.createSound();
                    }

                    //exinfo.length = (uint)data.data.Length;
                    //FMOD.MODE mode = FMOD.MODE.OPENMEMORY_POINT | FMOD.MODE.CREATECOMPRESSEDSAMPLE | FMOD.MODE.SOFTWARE;
                    //if (data._looping)
                    //    mode |= FMOD.MODE.LOOP_NORMAL;
                    //result = FMOD.Framework.system.createSound(data.data, mode, ref exinfo, ref mSound);

                    //ERRCHECK(result);

                    mSound = data.mSound;
                    if (mSound == null)
                    {
                        Dispose();
                        return;
                    }
                    GSGE.Debug.assert(mSound != null);

                    AudioEngine audioengine = GSGE.AudioManager.GetAudioManager().GetAudioEngine();
                    audioengine.FmodSounds.Add(this);

                    result = FMOD.Framework.system.playSound(FMOD.CHANNELINDEX.FREE, mSound, false, ref mChannel);
                    GSGE.Debug.assert(mSound != null);
                    ERRCHECK(result);
                    mChannel.getFrequency(ref mBaseFrequency);
                }
            }
#endif
        }
Exemplo n.º 35
0
        public void PerformBeatDetection(string musicFile, bool playOnFinish, ref float[] prunnedSpectralFlux, ref float[] beatTimes)
        {
            LoadSong(musicFile);

            lengthInMs = 0;
            FMOD_sound.getLength(ref lengthInMs, FMOD.TIMEUNIT.MS);

            frequency = GetFrequency(musicFile);

            {
                FMOD.SOUND_TYPE dummy_type = 0;
                FMOD.SOUND_FORMAT dummy_format = 0;
                FMOD_sound.getFormat(ref dummy_type, ref dummy_format, ref numChannels, ref byteDepth);
                byteDepth /= 8;
            }

            FMOD_sound.seekData(0);

            // complex
            ptrIn = fftwf.malloc(FFTW_WINDOW_SIZE * byteDepth * numChannels * 2);
            ptrOut = fftwf.malloc(FFTW_WINDOW_SIZE * byteDepth * numChannels * 2);

            FFTW_plan = fftwf.dft_1d(FFTW_WINDOW_SIZE, ptrIn, ptrOut, fftw_direction.Forward, fftw_flags.Estimate);

            if (byteDepth != 2)
            {
                Console.WriteLine("ERROR: files with bit depth other than 16 are not supported - Terminating");
                Environment.Exit(-1);
            }

            long numOutSamples = (long)Math.Ceiling(frequency * ((float)lengthInMs / 1000) / FFTW_WINDOW_SIZE);
            float[] spectralFlux = new float[numOutSamples];

            float[] hamming_window = new float[FFTW_WINDOW_SIZE];
            for (int i = 0; i < hamming_window.Length; ++i)
            {
                hamming_window[i] = hamming_alpha - (1.0f - hamming_alpha) * (float)Math.Cos((2.0f * Math.PI * i)
                    / (FFTW_WINDOW_SIZE - 1.0f));
            }

            int fftw_in_bytesize = FFTW_WINDOW_SIZE * byteDepth * numChannels;

            float[] fIn = new float[FFTW_WINDOW_SIZE];
            float[] fOut = new float[FFTW_WINDOW_SIZE / 2 + 1];
            float[] last_fout = new float[FFTW_WINDOW_SIZE / 2 + 1];

            uint bufferSize = (uint)((frequency * numChannels * byteDepth) * ((float)lengthInMs / 1000) + 1);
            IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize);

            uint bytesRead = 0;

            FMOD_sound.readData(buffer, bufferSize, ref bytesRead);

            long samples = bytesRead / (byteDepth * numChannels);

            // 16 bites audio fájloknál !!
            Int16[] intIn = new Int16[FFTW_WINDOW_SIZE * numChannels];

            int bufferSeekPos = 0;

            int counter = 0;
            while (samples >= FFTW_WINDOW_SIZE)
            {
                // átmásolunk FFTW_WINDOW_SIZE darabnyi sample-t egy integer tömbbe ahol
                // numChannel-enként vannak az új sample-ök
                Marshal.Copy(buffer + bufferSeekPos,
                    intIn,
                    0,
                    (int)FFTW_WINDOW_SIZE * (int)numChannels);

                // keeping track
                bufferSeekPos += fftw_in_bytesize;
                samples -= FFTW_WINDOW_SIZE;

                // az ideiglenes integer tömbből feltöltjük az FFTW által használt float input tömböt
                int sum = 0;
                for (int i = 0; i != FFTW_WINDOW_SIZE; i++)
                {
                    // nemfoglalkozunk külön a sávokkal, vesszük az átlaguk
                    sum = 0;
                    for (int j = 0; j != numChannels; j++)
                    {
                        sum += intIn[i * 2 + j];
                    }

                    // normalizáljuk (32768 <= 16bites hangfájlok, előjeles integer)
                    //	ha negatív akkor '-32767'-el kéne osztani
                    // a hamming window értékeit is itt számítjuk be ..google it
                    fIn[i] = ((sum / numChannels) / /*32768f*/65535f) * hamming_window[i];
                }

                // mivel az FFTW unmanaged memóriával dolgozik ezért odavissza kell másolgatni
                //	nekünk a memória mutatókkal elég kényelmetlen lenne dolgozni
                Marshal.Copy(fIn, 0, ptrIn, FFTW_WINDOW_SIZE);
                fftwf.execute(FFTW_plan);
                Marshal.Copy(ptrOut, fOut, 0, FFTW_WINDOW_SIZE / 2 + 1);

                // ezen ponton az 'fOut' tömb FFTW_WINDOW_SIZE darab sample frekvencia képét tartalmazza
                //	összesen 'FFTW_WINDOW_SIZE / 2 + 1' frekvencia sávra felosztva

                // a 'spectral flux' az az egyes frekvencia sávok változásai két sample window közt
                // itt fontos megjegyezni, hogy több 'spectralFlux'-hez hasonló tömböt is használhatnánk
                //	ha egyes frekencia tartományokra külön szeretnénk vizsgálni az értékeket (pl.: magas furulya hangok)
                float flux = 0;
                for (int i = 0; i < fOut.Length; i++)
                {
                    //float value = (fOut[i] - last_fout[i]);
                    float value = (Math.Abs(fOut[i]) - Math.Abs(last_fout[i]));

                    // a negatív értékeket nem vesszük figyelembe, csak a kiugrások érdekelnek
                    flux += value < 0 ? 0 : value;
                }
                spectralFlux[counter] = flux;

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

                counter++;
            }

            // felállítunk egy határértékét ami mindig az átlag 'spectral flux'
            //	azaz az átlag változások a frekvenciában
            // ezt megkell szorozni egy 1-nél nagyobb értékkel mert ami alatta van az kilesz dobva
            float[] threshold = new float[numOutSamples];

            for (int i = 0; i < spectralFlux.Length; i++)
            {
                int start = Math.Max(0, i - THRESHOLD_WINDOW_SIZE);
                int end = Math.Min(spectralFlux.Length - 1, i + THRESHOLD_WINDOW_SIZE);
                float mean = 0;
                for (int j = start; j <= end; j++)
                    mean += spectralFlux[j];
                mean /= (end - start);
                threshold[i] = mean * THRESHOLD_MULTIPLIER;
            }

            if (prunnedSpectralFlux != null)
            {
                // minden ami a threshold alatt van azt kidobjuk
                prunnedSpectralFlux = new float[numOutSamples];

                for (int i = 0; i < spectralFlux.Length; i++)
                {
                    if (threshold[i] <= spectralFlux[i])
                        prunnedSpectralFlux[i] = spectralFlux[i] - threshold[i];
                    else
                        prunnedSpectralFlux[i] = 0;
                }
            }

            if (beatTimes != null)
            {
                // mennyi időnek felel meg egy sample
                float sampleLengthInMs = (float)lengthInMs / numOutSamples;
                List<float> beatStamps = new List<float>();
                for (int i = 0; i < spectralFlux.Length; i++)
                {
                    if (threshold[i] <= spectralFlux[i])
                    {
                        beatStamps.Add(i * sampleLengthInMs);
                        spectralFlux[i] = spectralFlux[i] - threshold[i];
                    }
                    else
                    {
                        spectralFlux[i] = 0;
                    }
                }

                beatTimes = new float[beatStamps.Count];
                beatTimes = beatStamps.ToArray();
            }

            if (playOnFinish)
            {
                PlaySong(musicFile);
            }
            else
            {
                FMOD_sound.release();
                FMOD_sound = null;
                loadedMusicFile = "";
            }

            fftwf.free(ptrIn);
            fftwf.free(ptrOut);
            fftwf.destroy_plan(FFTW_plan);
            Marshal.FreeHGlobal(buffer);
        }
Exemplo n.º 36
0
        private void FMODreset()
        {
            FMOD.RESULT result;
            timer.Stop();
            FMODprogressBar.Value = 0;
            FMODtimerLabel.Text = "0:00.0 / 0:00.0";
            FMODstatusLabel.Text = "Stopped";
            FMODinfoLabel.Text = "";

            if (sound != null)
            {
                result = sound.release();
                if (result != FMOD.RESULT.OK) { StatusStripUpdate("FMOD error! " + result + " - " + FMOD.Error.String(result)); }
                sound = null;
            }
        }
Exemplo n.º 37
0
        private void selectAsset(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            previewPanel.BackgroundImage = global::Unity_Studio.Properties.Resources.preview;
            previewPanel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            assetInfoLabel.Visible = false;
            assetInfoLabel.Text = null;
            textPreviewBox.Visible = false;
            fontPreviewBox.Visible = false;
            FMODpanel.Visible = false;
            lastLoadedAsset = null;

            FMOD.RESULT result;
            if (sound != null)
            {
                result = sound.release();
                ERRCHECK(result);
            }
            sound = null;
            timer.Stop();
            FMODtimerLabel.Text = "0:00.0 / 0:00.0";
            FMODstatusLabel.Text = "Stopped";
            FMODprogressBar.Value = 0;
            FMODinfoLabel.Text = "";

            lastSelectedItem = (AssetPreloadData)e.Item;

            if (e.IsSelected)
            {
                assetInfoLabel.Text = lastSelectedItem.InfoText;
                if (displayInfo.Checked && assetInfoLabel.Text != null) { assetInfoLabel.Visible = true; } //only display the label if asset has info text

                if (enablePreview.Checked)
                {
                    lastLoadedAsset = lastSelectedItem;
                    PreviewAsset(lastLoadedAsset);
                }
            }
        }
Exemplo n.º 38
0
 public Sound(string name, FMOD.Sound FSound)
 {
     this.Name = name;
     this.FSound = FSound;
 }
Exemplo n.º 39
0
 /// <summary>
 /// Default constructor for Sound. Needs a pointer to the base FMOD.Sound 
 /// and the path to the audio file.
 /// </summary>        
 /// <param name="baseSound">Base FMOD.Sound</param>
 /// <param name="filePath">Audio file path</param>
 public Sound(FMOD.Sound baseSound, string filePath)
 {
     // Set private variables            
     this.m_baseSound = baseSound;
     this.m_filePath = filePath;
 }
Exemplo n.º 40
0
        /// <summary>
        /// Method responsible for disposing the variables that play the songs
        /// </summary>
        private void DisposeSound()
        {
            timer1.Stop();
            FMOD.RESULT result;

            if (sound != null)
            {
                result = sound.release();
                ERRCHECK(result);
            }
            sound = null;

            if (system != null)
            {
                result = system.close();
                ERRCHECK(result);

                result = system.release();
                ERRCHECK(result);
            }
            mydsp = null;
        }
Exemplo n.º 41
0
        // every level transition we dump all fmod data in an attempt to eliminate the silly bugs
        public void releaseSound()
        {
            if (mSound != null)
            {
                FMOD.RESULT result = mSound.release();
                ERRCHECK(result);
            }

            mSound = null;
        }
Exemplo n.º 42
0
 public void ReleaseSong()
 {
     if (FMOD_sound != null)
     {
         FMOD_sound.release();
         FMOD_sound = null;
         loadedMusicFile = "";
     }
 }
Exemplo n.º 43
0
        public ISoundEngine StopMusic()
        {
            if (this.analyzeChannel != null)
              {
            try
            {
              this.analyzeChannel.stop();
            }
            catch (Exception)
            {
              // Do nothing
            }

            this.analyzeChannel = null;
              }

              if (this.playChannel != null)
              {
            try
            {
              this.playChannel.stop();
            }
            catch (Exception)
            {
              // Do nothing
            }

            this.playChannel = null;
              }

              if (this.analyzeSound != null)
              {
            this.analyzeSound.release();
            this.analyzeSound = null;
              }

              if (this.playSound != null)
              {
            this.playSound.release();
            this.playSound = null;
              }

              return this;
        }
Exemplo n.º 44
0
 private void TTRUnloadSound()
 {
     if (TTRChannel != null)
     {
         // Bugfix: sound now only unloads if stopped
         if (GAPT_CurrentPlaybackState == "Stopped")
         {
             TTRSound.release();
             TTRUpdateText_Row3_Sub("No track is currently loaded.");
             TTRUpdateText_Row1_Sub(" ");
             TTRUpdateText_Row2_Sub(" ");
             TTRSound = null;
             TTRChannel = null;
             TTRLength = 0;
             GAPT_LastPROCESSEDName = "";
             GAPT_LastTrackName = "";
         }
     }
 }
Exemplo n.º 45
0
        // instances only dispose of streaming audio
        public void Dispose()
        {
#if !NO_FMOD
            if (Playing && mChannel != null)
            {
                mChannel.stop();
            }

            if (mSound != null)
            {
                AudioEngine audioengine = GSGE.AudioManager.GetAudioManager().GetAudioEngine();
                audioengine.FmodSounds.Remove(this);
            }

            if (mOwnSound && mSound != null)
            {
                FMOD.RESULT result = mSound.release();
                ERRCHECK(result);
            }

            mOwnSound = false;
            mSound = null;
            mChannel = null;

            if (mStreamRequested != mStreamStarted)
                mAbortStream = true;
            else
            {
                mStreamBytes = null;
                mStreamRequested = false;
                mStreamStarted = false;
            }
#endif
        }
Exemplo n.º 46
0
        private void timer_Tick(object sender, System.EventArgs e)
        {
            FMOD.RESULT     result;
            FMOD.OPENSTATE  openstate = 0;

            if (soundcreated)
            {
                uint percentbuffered = 0;
                bool starving = false;
                bool busy = false;

                result = sound.getOpenState(ref openstate, ref percentbuffered, ref starving, ref busy);
                ERRCHECK(result);

                if (openstate == FMOD.OPENSTATE.READY && channel == null)
                {
                    result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel);
                    ERRCHECK(result);
                }
            }

            if (channel != null)
            {
                uint ms      = 0;
                bool playing = false;
                bool paused  = false;
                int  tagsupdated = 0;
                int  numtags = 0;

                result = sound.getNumTags(ref numtags, ref tagsupdated);
                ERRCHECK(result);

                if (tagsupdated != 0)
                {
                    for (;;)
                    {
                        FMOD.TAG tag = new FMOD.TAG();

                        if (sound.getTag(null, -1, ref tag) != FMOD.RESULT.OK)
                        {
                            break;
                        }

                        if (tag.datatype == FMOD.TAGDATATYPE.STRING)
                        {
                            FMOD.SOUND_FORMAT   format = FMOD.SOUND_FORMAT.NONE;
                            int                 channels = 0;
                            int                 bits = 0;

                            sound.getFormat(ref gSoundType, ref format, ref channels, ref bits);

                            if (tag.name == "ARTIST")
                            {
                                if (Marshal.PtrToStringAnsi(tag.data) != gCurrentTrackArtist)
                                {
                                    gCurrentTrackArtist = Marshal.PtrToStringAnsi(tag.data);
                                    gUpdateFileName = true;
                                }
                            }
                            if (tag.name == "TITLE")
                            {
                                if (Marshal.PtrToStringAnsi(tag.data) != gCurrentTrackTitle)
                                {
                                    gCurrentTrackTitle = Marshal.PtrToStringAnsi(tag.data);
                                    gUpdateFileName = true;
                                }
                            }
                            break;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                result = channel.isPlaying(ref playing);
                if (result != FMOD.RESULT.OK || !playing)
                {
                    sound.release();
                    sound = null;
                    channel = null;
                }
                else
                {
                    result = channel.getPaused(ref paused);
                    ERRCHECK(result);
                    result = channel.getPosition(ref ms, FMOD.TIMEUNIT.MS);
                    ERRCHECK(result);

                    statusBar.Text = "Time " + (ms /1000 / 60) + ":" + (ms / 1000 % 60) + ":" + (ms / 10 % 100) + (paused ? " Paused " : playing ? " Playing" : " Stopped");
                }
            }

            if (sound != null)
            {
                uint percentbuffered = 0;
                bool starving = false;
                bool busy = false;

                sound.getOpenState(ref openstate, ref percentbuffered, ref starving, ref busy);

                if (openstate == FMOD.OPENSTATE.ERROR)
                {
                    sound.release();
                    sound = null;
                    channel = null;
                }
            }

            if (openstate == FMOD.OPENSTATE.ERROR)
            {
                statusBar.Text = "Error occurred or stream ended.  Restarting stream..";
                result = system.createSound(url, (FMOD.MODE.HARDWARE | FMOD.MODE._2D | FMOD.MODE.CREATESTREAM | FMOD.MODE.NONBLOCKING), ref exinfo, ref sound);
                ERRCHECK(result);
            }

            if (system != null)
            {
                system.update();
            }
        }
 ///<summary>
 ///    Make sure to free the sound and the codec
 ///</summary>
 public void Dispose()
 {
     disposing = true;
     lock(voiceMgr.usingFmod) {
         sourceReady = false;
         StopRecording(channelSound);
         if (playbackStream != null) {
             playbackStream.Close();
             playbackStream = null;
             playbackFile = "";
         }
         log.Debug(voiceMgr, "BasicChannel.Dispose called");
         if (channel != null) {
             CheckRetCode("Stopping the FMOD channel in BasicChannel.Dispose()", channel.stop());
             channel = null;
         }
         if (channelSound != null) {
             CheckRetCode("Releasing the FMOD sound in BasicChannel.Dispose()", channelSound.release());
             channelSound = null;
         }
         if (channelCodec != null) {
             channelCodec.ResetEncoder();
             channelCodec = null;
         }
     }
 }
Exemplo n.º 48
0
        private void FMODinit()
        {
            FMOD.RESULT result;
            timer.Stop();
            FMODtimerLabel.Text = "0:00.0 / 0:00.0";
            FMODstatusLabel.Text = "Stopped";
            FMODprogressBar.Value = 0;

            if (sound != null)
            {
                result = sound.release();
                ERRCHECK(result);
                sound = null;
            }

            uint version = 0;

            result = FMOD.Factory.System_Create(ref system);
            ERRCHECK(result);

            result = system.getVersion(ref version);
            ERRCHECK(result);
            if (version < FMOD.VERSION.number)
            {
                MessageBox.Show("Error!  You are using an old version of FMOD " + version.ToString("X") + ".  This program requires " + FMOD.VERSION.number.ToString("X") + ".");
                Application.Exit();
            }

            result = system.init(1, FMOD.INITFLAGS.NORMAL, (IntPtr)null);
            ERRCHECK(result);

            result = system.getMasterSoundGroup(ref masterSoundGroup);
            ERRCHECK(result);

            result = masterSoundGroup.setVolume(FMODVolume);
            ERRCHECK(result);
        }
Exemplo n.º 49
0
 public FmodSound(FmodAudio a, FMOD.Sound s, bool stream)
     : base(a)
 {
     sound = s;
     IsStream = stream;
 }