示例#1
0
        // ========================================================================================================================================
        #region Start / Stop

        void StartFMODSound(int sampleRate)
        {
            this.StopFMODSound();

            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            // exinfo.cbsize = sizeof(FMOD.CREATESOUNDEXINFO);
            exinfo.numchannels       = this.unityOAFRChannels;                                                              /* Number of channels in the sound. */
            exinfo.defaultfrequency  = sampleRate;                                                                          /* Default playback rate of sound. */
            exinfo.decodebuffersize  = (uint)this.unityOAFRDataLength;                                                      /* Chunk size of stream update in samples. This will be the amount of data passed to the user callback. */
            exinfo.length            = (uint)(exinfo.defaultfrequency * exinfo.numchannels * this.elementSize);             /* Length of PCM data in bytes of whole song (for Sound::getLength) */
            exinfo.format            = FMOD.SOUND_FORMAT.PCM16;                                                             /* Data format of sound. */
            exinfo.pcmreadcallback   = this.pcmreadcallback;                                                                /* User callback for reading. */
            exinfo.pcmsetposcallback = this.pcmsetposcallback;                                                              /* User callback for seeking. */

            result = system.createSound(""
                                        , FMOD.MODE.OPENUSER
                                        | FMOD.MODE.CREATESTREAM
                                        | FMOD.MODE.LOOP_NORMAL
                                        , ref exinfo
                                        , out sound);
            AudioStreamSupport.ERRCHECK(result, this.logLevel, this.gameObjectName, null, "system.createSound");

            AudioStreamSupport.LOG(LogLevel.DEBUG, this.logLevel, this.gameObjectName, null, "About to play...");

            result = system.playSound(sound, null, false, out channel);
            AudioStreamSupport.ERRCHECK(result, this.logLevel, this.gameObjectName, null, "system.playSound");
        }
示例#2
0
文件: Utility.cs 项目: kkdevs/sb3u
 public void Play(string name, byte[] soundBuf)
 {
     FMOD.CREATESOUNDEXINFO sndInfo = new FMOD.CREATESOUNDEXINFO()
     {
         length = (uint)soundBuf.Length,
     };
     FMOD.RESULT result = system.createSound(soundBuf, FMOD.MODE.OPENMEMORY, ref sndInfo, out sound);
     ERRCHECK(result, "system.createSound");
     if (result == FMOD.RESULT.OK)
     {
         int numSubSounds;
         result = sound.getNumSubSounds(out numSubSounds);
         ERRCHECK(result, "sound.getNumSubSounds");
         if (numSubSounds > 0)
         {
             result = sound.getSubSound(0, out subSound);
             ERRCHECK(result, "sound.getSubSound");
             result = system.playSound(subSound, null, false, out channel);
         }
         else
         {
             result = system.playSound(sound, null, false, out channel);
         }
         ERRCHECK(result, "sound.playSound");
     }
 }
        private void Form1_Load(object sender, System.EventArgs e)
        {
            uint version = 0;

            FMOD.RESULT result;
            int         length;

            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();

            /*
             *  Global Settings
             */
            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);

            length = LoadFileIntoMemory("../../../../../examples/media/wave.mp3");

            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = (uint)length;

            result = system.createSound(audiodata, (FMOD.MODE.HARDWARE | FMOD.MODE.OPENMEMORY), ref exinfo, ref sound);
            ERRCHECK(result);
        }
示例#4
0
        private void comboBoxRecord_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            FMOD.RESULT            result;
            selected = comboBoxRecord.SelectedIndex;

            comboBoxOutput.Enabled = false;
            comboBoxRecord.Enabled = false;

            /*
             *  Initialise
             */
            result = system.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null);
            ERRCHECK(result);

            exinfo.cbsize           = Marshal.SizeOf(exinfo);
            exinfo.numchannels      = 2;
            exinfo.format           = FMOD.SOUND_FORMAT.PCM16;
            exinfo.defaultfrequency = 44100;
            exinfo.length           = (uint)(exinfo.defaultfrequency * 2 * exinfo.numchannels * 2);

            result = system.createSound((string)null, (FMOD.MODE._2D | FMOD.MODE.SOFTWARE | FMOD.MODE.OPENUSER), ref exinfo, ref sound);
            ERRCHECK(result);

            start.Enabled = true;
        }
示例#5
0
文件: Sound.cs 项目: PDecker1/mario
        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);
        }
示例#6
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;
        }
示例#7
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
示例#8
0
        public static void LoadSound(int id, byte[] data)
        {
            var exinfo = new FMOD.CREATESOUNDEXINFO();

            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = (uint)data.Length;
            var result = FMODUnity.RuntimeManager.CoreSystem.createSound(data, FMOD.MODE._2D | FMOD.MODE.OPENMEMORY, ref exinfo, out FMOD.Sound sound);

            if (result == FMOD.RESULT.OK)
            {
                SoundList[id] = sound;
            }
        }
示例#9
0
        private void comboBoxRecord_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            FMOD.RESULT            result;
            FMOD.DSP_RESAMPLER     resampler = FMOD.DSP_RESAMPLER.MAX;
            int selected = comboBoxRecord.SelectedIndex;
            int temp     = 0;

            FMOD.SOUND_FORMAT format = FMOD.SOUND_FORMAT.NONE;

            result = system.setSoftwareFormat(OUTPUTRATE, FMOD.SOUND_FORMAT.PCM16, 1, 0, 0);
            ERRCHECK(result);

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

            result = system.getSoftwareFormat(ref outputfreq, ref format, ref temp, ref temp, ref resampler, ref temp);
            ERRCHECK(result);

            /*
             *  Create a sound to record to.
             */
            exinfo.cbsize           = Marshal.SizeOf(exinfo);
            exinfo.numchannels      = 1;
            exinfo.format           = FMOD.SOUND_FORMAT.PCM16;
            exinfo.defaultfrequency = OUTPUTRATE;
            exinfo.length           = (uint)(exinfo.defaultfrequency * 2 * exinfo.numchannels * 5);

            result = system.createSound((string)null, (FMOD.MODE._2D | FMOD.MODE.SOFTWARE | FMOD.MODE.LOOP_NORMAL | FMOD.MODE.OPENUSER), ref exinfo, ref sound);
            ERRCHECK(result);

            comboBoxOutput.Enabled   = false;
            comboBoxPlayback.Enabled = false;
            comboBoxRecord.Enabled   = false;

            /*
             *  Start recording
             */
            result = system.recordStart(selected, sound, true);
            ERRCHECK(result);

            Thread.Sleep(200);      /* Give it some time to record something */

            result = system.playSound(FMOD.CHANNELINDEX.REUSE, sound, false, ref channel);
            ERRCHECK(result);

            /* Dont hear what is being recorded otherwise it will feedback.  Spectrum analysis is done before volume scaling in the DSP chain */
            result = channel.setVolume(0);
            ERRCHECK(result);
        }
示例#10
0
        /// <summary>
        /// Loads sound from file.
        /// Use this function to load short sound effects.
        /// </summary>
        public static Sound LoadSound(string name)
        {
            var buffer = LoadFileAsBuffer(Path.Combine(_rootDir, name));

            var info = new FMOD.CREATESOUNDEXINFO();

            info.length = (uint)buffer.Length;
            info.cbsize = Marshal.SizeOf(info);

            FMODSystem.createSound(
                buffer,
                FMOD.MODE.OPENMEMORY | FMOD.MODE.CREATESAMPLE,
                ref info,
                out FMOD.Sound newSound
                );

            return(new Sound(newSound));
        }
示例#11
0
        /// <summary>
        /// Loads sound from file.
        /// Use this function to load short sound effects.
        /// </summary>
        public static Sound LoadSound(string path)
        {
            var buffer = FileLoader.LoadFileAsBuffer(path);

            var info = new FMOD.CREATESOUNDEXINFO();

            info.length = (uint)buffer.Length;
            info.cbsize = Marshal.SizeOf(info);

            Native.createSound(
                buffer,
                FMOD.MODE.OPENMEMORY | FMOD.MODE.CREATESAMPLE,
                ref info,
                out FMOD.Sound newSound
                );

            return(new Sound(newSound));
        }
示例#12
0
        public Sound Load(Stream s)
        {
            byte[] buffer = new byte[s.Length];
            s.Read(buffer, 0, (int)s.Length);

            FMOD.RESULT            result;
            FMOD.Sound             sound1 = null;
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = (uint)s.Length;

            //result = system.createSound(buffer, (FMOD.MODE.HARDWARE | FMOD.MODE._3D | FMOD.MODE.OPENMEMORY), ref exinfo, ref sound1);
            result = system.createSound(buffer, (FMOD.MODE.HARDWARE | FMOD.MODE._3D | FMOD.MODE.OPENMEMORY | FMOD.MODE._3D_LINEARROLLOFF), ref exinfo, ref sound1);
            ERRCHECK(result);

            sound1.set3DMinMaxDistance(500, 5000);
            return(new FmodSound(this, sound1, false));
        }
示例#13
0
        public static void PlaySound(byte[] data, bool isLoop)
        {
            StopSound();
            var exinfo = new FMOD.CREATESOUNDEXINFO();

            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = (uint)data.Length;
            var result = FMODUnity.RuntimeManager.CoreSystem.createSound(data, FMOD.MODE._2D | FMOD.MODE.OPENMEMORY | (isLoop ? FMOD.MODE.LOOP_NORMAL : 0), ref exinfo, out FMOD.Sound sound);

            if (result == FMOD.RESULT.OK)
            {
                shareSound = sound;
                var result2 = FMODUnity.RuntimeManager.CoreSystem.playSound(sound, Game, false, out FMOD.Channel channel);
                if (result2 == FMOD.RESULT.OK)
                {
                    shareChannel = channel;
                }
            }
        }
示例#14
0
		public void Output(int channel, IntPtr buffer, bool block, int volume)
		{
			FMOD.RESULT result;

			Debug.Assert(channel >= 0 && channel <= 7);
			if (this.Channels[channel].Reserved == false)
			{
				return;
			}
			
			if (this.Channels[channel].Channel != null)
			{
				this.Channels[channel].Channel.stop();
				this.Channels[channel].Channel = null;
			}
			
			if (this.Channels[channel].Sound != null)
			{
				this.Channels[channel].Sound.release();
				this.Channels[channel].Sound = null;
			}

			uint size = (uint)(this.Channels[channel].SampleCount * 2 * 2);
			
			FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
			exinfo.cbsize = Marshal.SizeOf(exinfo);
			exinfo.length = size;
			exinfo.numchannels = this.Channels[channel].Format == AudioFormat.Mono ? 1 : 2;
			exinfo.defaultfrequency = 44100;
			exinfo.format = FMOD.SOUND_FORMAT.PCM16;
			exinfo.suggestedsoundtype = FMOD.SOUND_TYPE.RAW;

			result = this.AudioSystem.createSound(buffer, FMOD.MODE.OPENMEMORY | FMOD.MODE.OPENRAW | FMOD.MODE.CREATESAMPLE | FMOD.MODE.SOFTWARE | FMOD.MODE._2D, ref exinfo, ref this.Channels[channel].Sound);
			Debug.Assert(result == FMOD.RESULT.OK);
			result = this.AudioSystem.playSound(FMOD.CHANNELINDEX.REUSE, this.Channels[channel].Sound, false, ref this.Channels[channel].Channel);
			Debug.Assert(result == FMOD.RESULT.OK);

			//using (FileStream stream = File.OpenWrite(String.Format("sound_test_{0}.bin", counter++)))
			//using (BinaryWriter writer = new BinaryWriter(stream))
			//{
			//    writer.Write(bytes);
			//}
		}
示例#15
0
        private void StreamInit(string connectionUrl, FMOD.SOUND_PCMREADCALLBACK pcmReadCallback, FMOD.SOUND_PCMSETPOSCALLBACK pcmSetPosCallback) // loading stream data
        {
            thisLock        = new Object();
            SoundDataBuffer = new CircularBuffer(defaultSize);

            FMOD.CREATESOUNDEXINFO exInfo = new FMOD.CREATESOUNDEXINFO();
            exInfo.cbsize = Marshal.SizeOf(exInfo);
            //   exInfo.length = (uint)(SoundDataBuffer.Buffer.Length * sizeof(short));
            exInfo.numchannels       = channelCount;
            exInfo.fileoffset        = 0;
            exInfo.format            = FMOD.SOUND_FORMAT.PCM16;
            exInfo.defaultfrequency  = frequency;
            exInfo.pcmreadcallback   = pcmReadCallback;
            exInfo.pcmsetposcallback = pcmSetPosCallback;
            exInfo.dlsname           = null;

            FMOD.RESULT result = system.createSound(connectionUrl, (FMOD.MODE.HARDWARE | FMOD.MODE._2D | FMOD.MODE.CREATESTREAM | FMOD.MODE.NONBLOCKING), ref exInfo, ref sounds);
            ErrorCheck(result);
        }
示例#16
0
        public void SoundInit(FMOD.SOUND_PCMREADCALLBACK pcmReadCallback, FMOD.SOUND_PCMSETPOSCALLBACK pcmSetPosCallback)  // providing data to stream
        {
            SoundDataBuffer = new CircularBuffer(defaultSize);
            thisLock        = new Object();

            FMOD.CREATESOUNDEXINFO exInfo = new FMOD.CREATESOUNDEXINFO();
            exInfo.cbsize            = Marshal.SizeOf(exInfo);
            exInfo.length            = (uint)(SoundDataBuffer.Buffer.Length * sizeof(short));
            exInfo.numchannels       = channelCount;
            exInfo.fileoffset        = 0;
            exInfo.format            = FMOD.SOUND_FORMAT.PCM16;
            exInfo.defaultfrequency  = frequency;
            exInfo.pcmreadcallback   = pcmReadCallback;
            exInfo.pcmsetposcallback = pcmSetPosCallback;
            exInfo.dlsname           = null;

            FMOD.RESULT result = system.createSound((string)null, (FMOD.MODE.CREATESTREAM | FMOD.MODE.OPENUSER | FMOD.MODE.OPENRAW | FMOD.MODE._2D | FMOD.MODE.LOOP_NORMAL), ref exInfo, ref sounds);
            ErrorCheck(result);
        }
示例#17
0
        /// <summary>
        /// Loads streamed sound stream from file.
        /// Use this function to load music and long ambience tracks.
        /// </summary>
        public static Sound LoadStreamedSound(string path)
        {
            var buffer = FileLoader.LoadFileAsBuffer(path);

            // Internal FMOD pointer points to this memory, so we don't want it to go anywhere.
            var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

            var info = new FMOD.CREATESOUNDEXINFO();

            info.length = (uint)buffer.Length;
            info.cbsize = Marshal.SizeOf(info);

            Native.createStream(
                buffer,
                FMOD.MODE.OPENMEMORY | FMOD.MODE.CREATESTREAM,
                ref info,
                out FMOD.Sound newSound
                );

            return(new Sound(newSound, buffer, handle));
        }
示例#18
0
        public void LoadAnySound(SoundResource soundResource, string fullPath)
        {
            //FMOD.MODE flags = FMOD.MODE.HARDWARE;
            FMOD.MODE flags = FMOD.MODE.SOFTWARE | FMOD.MODE._3D_LINEARROLLOFF;
            if (soundResource.Is3DSound)
            {
                flags |= FMOD.MODE._3D | FMOD.MODE._3D_IGNOREGEOMETRY;
            }
            else
            {
                flags |= FMOD.MODE._2D;
            }

            FMOD.Sound sound = new FMOD.Sound();
            soundResource.SoundGlue = new FMODSound(sound);
            if (soundResource.IsStream)
            {
                flags  = FMOD.MODE.SOFTWARE;
                flags |= FMOD.MODE.CREATESTREAM | FMOD.MODE.NONBLOCKING;
                FMOD.CREATESOUNDEXINFO createSoundExInfo = new FMOD.CREATESOUNDEXINFO();
                createSoundExInfo.cbsize           = System.Runtime.InteropServices.Marshal.SizeOf(typeof(FMOD.CREATESOUNDEXINFO));
                createSoundExInfo.nonblockcallback = NonBlockCallback;
                ERRCHECK(FMODSystem.createSound(fullPath, flags, ref createSoundExInfo, ref sound));
                int index = sound.getRaw().ToInt32();
                try
                {
                    loadingSoundResources[index] = soundResource;
                }
                catch (IndexOutOfRangeException)
                {
                    System.Diagnostics.Debugger.Break();        // please report the value of the index-variable defined above
                }
            }
            else
            {
                ERRCHECK(FMODSystem.createSound(fullPath, flags, ref sound));
                InitiateLoadedSound(soundResource);
            }
        }
示例#19
0
        protected void TTRPlaySound(string Argument0, uint Argument1, uint Argument2, bool Argument3)
        {
            try
            {
                string oogimaflip_001;
                string oogimaflip_002;
                FMOD.RESULT result;

                int TTRNull = 0;

                GAPT_LastTrackName = Argument0;

                GAPT_CurrentTrackTitle = Path.GetFileName(Argument0);

                GAPT_CurrentLoopStart = Argument1;
                GAPT_CurrentLoopDone = Argument2;

                FMOD.CREATESOUNDEXINFO ex = new FMOD.CREATESOUNDEXINFO();
                ex.cbsize = Marshal.SizeOf(ex);

                if (CurrentDLSFile != "")
                {
                    ex.dlsname = CurrentDLSFile;
                }

                if (radioButton3.Checked)
                {
                    result = system.createSound(Argument0, FMOD.MODE.SOFTWARE | FMOD.MODE._2D | FMOD.MODE.CREATESTREAM | FMOD.MODE.NONBLOCKING, ref ex, ref TTRSound);
                }
                else
                {
                    result = system.createSound(Argument0, FMOD.MODE.SOFTWARE | FMOD.MODE._2D | FMOD.MODE.CREATESTREAM, ref ex, ref TTRSound);
                }

                ERRCHECK(result);

                while (radioButton3.Checked)
                {
                    result = TTRSound.getOpenState(ref a, ref b, ref c);
                    ERRCHECK(result);

                    if (a == FMOD.OPENSTATE.READY && TTRChannel == null)
                    {
                        break;
                    }

                }

                result = TTRSound.setLoopPoints(GAPT_CurrentLoopStart, FMOD.TIMEUNIT.MS, GAPT_CurrentLoopDone, FMOD.TIMEUNIT.MS);
                ERRCHECK(result);

                if (radioButton2.Checked)
                {
                    result = TTRSound.setMode(FMOD.MODE.LOOP_NORMAL | FMOD.MODE.ACCURATETIME);
                }
                else
                {
                    result = TTRSound.setMode(FMOD.MODE.LOOP_OFF | FMOD.MODE.ACCURATETIME);
                }

                result = system.playSound(FMOD.CHANNELINDEX.REUSE, TTRSound, Argument3, ref TTRChannel);
                ERRCHECK(result);

                if (trackBar1.InvokeRequired)
                {
                    trackBar1.Invoke(new DFCADelegate(this.TTRUpdateSoundVolume), null);
                }
                else
                {
                    TTRUpdateSoundVolume();
                }

                result = TTRSound.getLength(ref TTRLength, FMOD.TIMEUNIT.MS);
                ERRCHECK(result);

                result = TTRSound.getNumTags(ref TTRNumTags, ref TTRNumTagsUpdated);
                ERRCHECK(result);

                if (checkBox2.Checked)
                {
                    result = TTRSound.getTag("TIT2", -1, ref TTRDataTag);
                    if (result != FMOD.RESULT.ERR_TAGNOTFOUND)
                    {
                        ERRCHECK(result);
                        oogimaflip_001 = Marshal.PtrToStringAnsi(TTRDataTag.data);
                        if (oogimaflip_001.StartsWith("ÿþ"))
                        {
                            oogimaflip_001 = Marshal.PtrToStringUni(TTRDataTag.data);
                        }
                    }
                    else
                    {
                        result = TTRSound.getTag("TIT1", -1, ref TTRDataTag);
                        if (result != FMOD.RESULT.ERR_TAGNOTFOUND)
                        {
                            ERRCHECK(result);
                            oogimaflip_001 = Marshal.PtrToStringAnsi(TTRDataTag.data);
                            if (oogimaflip_001.StartsWith("ÿþ"))
                            {
                                oogimaflip_001 = Marshal.PtrToStringUni(TTRDataTag.data);
                            }
                        }
                        else
                        {
                            result = TTRSound.getTag("TITLE", -1, ref TTRDataTag);
                            if (result != FMOD.RESULT.ERR_TAGNOTFOUND)
                            {
                                ERRCHECK(result);
                                oogimaflip_001 = Marshal.PtrToStringAnsi(TTRDataTag.data);
                                if (oogimaflip_001.StartsWith("ÿþ"))
                                {
                                    oogimaflip_001 = Marshal.PtrToStringUni(TTRDataTag.data);
                                }
                            }
                            else
                            {
                                // Title tag is not present
                                if (radioButton3.Checked)
                                {
                                    oogimaflip_001 = "Online Broadcasting";
                                }
                                else
                                {
                                    oogimaflip_001 = Path.GetFileName(Argument0);
                                }
                            }
                        }
                    }

                    result = TTRSound.getTag("TPE2", -1, ref TTRDataTag);
                    if (result != FMOD.RESULT.ERR_TAGNOTFOUND)
                    {
                        ERRCHECK(result);
                        oogimaflip_002 = Marshal.PtrToStringAnsi(TTRDataTag.data) + " - ";
                        if (oogimaflip_002.StartsWith("ÿþ"))
                        {
                            oogimaflip_002 = Marshal.PtrToStringUni(TTRDataTag.data) + " - ";
                        }
                    }
                    else
                    {
                        result = TTRSound.getTag("TPE1", -1, ref TTRDataTag);
                        if (result != FMOD.RESULT.ERR_TAGNOTFOUND)
                        {
                            ERRCHECK(result);
                            oogimaflip_002 = Marshal.PtrToStringAnsi(TTRDataTag.data) + " - ";
                            if (oogimaflip_002.StartsWith("ÿþ"))
                            {
                                oogimaflip_002 = Marshal.PtrToStringUni(TTRDataTag.data) + " - ";
                            }
                        }
                        else
                        {
                            result = TTRSound.getTag("ARTIST", -1, ref TTRDataTag);
                            if (result != FMOD.RESULT.ERR_TAGNOTFOUND)
                            {
                                ERRCHECK(result);
                                oogimaflip_002 = Marshal.PtrToStringAnsi(TTRDataTag.data) + " - ";
                                if (oogimaflip_002.StartsWith("ÿþ"))
                                {
                                    oogimaflip_002 = Marshal.PtrToStringUni(TTRDataTag.data) + " - ";
                                }
                            }
                            else
                            {
                                oogimaflip_002 = "";
                            }
                        }
                    }

                    if (radioButton3.Checked)
                    {
                        GAPT_CurrentTrackTitle = "Ginever Radio: " + oogimaflip_002.Replace("&", "&&") + oogimaflip_001.Replace("&", "&&");
                    }
                    else
                    {
                        GAPT_CurrentTrackTitle = oogimaflip_002.Replace("&", "&&") + oogimaflip_001.Replace("&", "&&");
                    }

                }
                else
                {
                    if (radioButton3.Checked)
                    {
                        GAPT_CurrentTrackTitle = "Ginever Radio";
                    }
                    else
                    {
                        GAPT_CurrentTrackTitle = Path.GetFileName(Argument0);
                    }
                }

                result = TTRSound.getFormat(ref TTRSoundType, ref TTRSoundFormat, ref TTRNull, ref TTRNull);
                ERRCHECK(result);

                TTRFetchSoundTypeTextifier();
                TTRFetchTrackFilesize();

               /* try
                {
                  //  float queenie = 0;
                   // TTRChannel.getFrequency(ref queenie);
                   // TTRChannel.setFrequency(queenie*0.95f);

                    TTRChannel.addDSP(keyMinus1, ref TTRDSPNull);
                }
                catch
                {
                    MessageBox(new IntPtr(0), "Non-critical Exception Raised: GAPI_SETFREQ_FAILURE" + Environment.NewLine + "Failed to set track frequency.", "GSA Exception Trapper", MB_OK | ICON_INFORMATION);
                }*/

                if (Argument3)
                {
                    GAPT_CurrentPlaybackState = "Paused";
                }
                else
                {
                    GAPT_CurrentPlaybackState = "Playing";
                }
            }
            catch
            {
                MessageBox(new IntPtr(0), "Non-critical Exception Raised: GAPI_PLAY_FAILURE" + Environment.NewLine + "Failed to play requested track.", "GSA Exception Trapper", MB_OK | ICON_INFORMATION);
            }
        }
        private void comboBoxRecord_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            FMOD.RESULT result;
            FMOD.DSP_RESAMPLER  resampler = FMOD.DSP_RESAMPLER.MAX;
            int selected = comboBoxRecord.SelectedIndex;
            int temp = 0;
            FMOD.SOUND_FORMAT format = FMOD.SOUND_FORMAT.NONE;

            result = system.setSoftwareFormat(OUTPUTRATE, FMOD.SOUND_FORMAT.PCM16, 1, 0, 0);
            ERRCHECK(result);

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

            result = system.getSoftwareFormat(ref outputfreq, ref format, ref temp, ref temp, ref resampler, ref temp);
            ERRCHECK(result);

            /*
                Create a sound to record to.
            */
            exinfo.cbsize           = Marshal.SizeOf(exinfo);
            exinfo.numchannels      = 1;
            exinfo.format           = FMOD.SOUND_FORMAT.PCM16;
            exinfo.defaultfrequency = OUTPUTRATE;
            exinfo.length           = (uint)(exinfo.defaultfrequency * 2 * exinfo.numchannels * 5);

            result = system.createSound((string)null, (FMOD.MODE._2D | FMOD.MODE.SOFTWARE | FMOD.MODE.LOOP_NORMAL | FMOD.MODE.OPENUSER), ref exinfo, ref sound);
            ERRCHECK(result);

            comboBoxOutput.Enabled = false;
            comboBoxPlayback.Enabled = false;
            comboBoxRecord.Enabled = false;

            /*
                Start recording
            */
            result = system.recordStart(selected, sound, true);
            ERRCHECK(result);

            Thread.Sleep(200);      /* Give it some time to record something */

            result = system.playSound(FMOD.CHANNELINDEX.REUSE, sound, false, ref channel);
            ERRCHECK(result);

            /* Dont hear what is being recorded otherwise it will feedback.  Spectrum analysis is done before volume scaling in the DSP chain */
            result = channel.setVolume(0);
            ERRCHECK(result);
        }
示例#21
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            FMOD.RESULT            result;
            uint version = 0;

            /*
             *  Create a System object and initialize.
             */
            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);

            /*
             *  Set up the FMOD_CREATESOUNDEXINFO structure for the user stream with room for 2 subsounds. (our subsound double buffer)
             */

            exinfo.cbsize           = Marshal.SizeOf(exinfo);
            exinfo.defaultfrequency = 44100;
            exinfo.numsubsounds     = 2;
            exinfo.numchannels      = 1;
            exinfo.format           = FMOD.SOUND_FORMAT.PCM16;

            /*
             *  Create the 'parent' stream that contains the substreams.  Set it to loop so that it loops between subsound 0 and 1.
             */
            result = system.createStream("", FMOD.MODE.LOOP_NORMAL | FMOD.MODE.OPENUSER, ref exinfo, ref sound);
            ERRCHECK(result);

            /*
             *  Add 2 of our streams as children of the parent.  They should be the same format (ie mono/stereo and bitdepth) as the parent sound.
             *  When subsound 0 has finished and it is playing subsound 1, we will swap subsound 0 with a new sound, and the same for when subsound 1 has finished,
             *  causing a continual double buffered flip, which means continuous sound.
             */
            result = system.createStream(soundname[0], FMOD.MODE.DEFAULT, ref subsound[0]);
            ERRCHECK(result);

            result = system.createStream(soundname[1], FMOD.MODE.DEFAULT, ref subsound[1]);
            ERRCHECK(result);

            result = sound.setSubSound(0, subsound[0]);
            ERRCHECK(result);

            result = sound.setSubSound(1, subsound[1]);
            ERRCHECK(result);

            /*
             *  Set up the gapless sentence to contain these first 2 streams.
             */
            {
                int[] soundlist = { 0, 1 };

                result = sound.setSubSoundSentence(soundlist, 2);
                ERRCHECK(result);
            }

            subsoundid = 0;
            sentenceid = 2;     /* The next sound to be appeneded to the stream. */

            /*
             *  Play the sound.
             */

            result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel);
            ERRCHECK(result);
        }
        private void Form1_Load(object sender, System.EventArgs e)
        {
            uint                   version = 0;
            FMOD.RESULT            result;
            int                    length;
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();

            /*
                Global Settings
            */
            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);

            length = LoadFileIntoMemory("../../../../../examples/media/wave.mp3");

            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = (uint)length;

            result = system.createSound(audiodata, (FMOD.MODE.HARDWARE | FMOD.MODE.OPENMEMORY), ref exinfo, ref sound);
            ERRCHECK(result);
        }
        private void comboBoxRecord_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            FMOD.RESULT result;
            selected = comboBoxRecord.SelectedIndex;

            comboBoxOutput.Enabled = false;
            comboBoxRecord.Enabled = false;

            /*
                Initialise
            */
            result = system.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null);
            ERRCHECK(result);

            exinfo.cbsize           = Marshal.SizeOf(exinfo);
            exinfo.numchannels      = 2;
            exinfo.format           = FMOD.SOUND_FORMAT.PCM16;
            exinfo.defaultfrequency = 44100;
            exinfo.length           = (uint)(exinfo.defaultfrequency * 2 * exinfo.numchannels * 2);

            result = system.createSound((string)null, (FMOD.MODE._2D | FMOD.MODE.SOFTWARE | FMOD.MODE.OPENUSER), ref exinfo, ref sound);
            ERRCHECK(result);

            start.Enabled = true;
        }
示例#24
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
        }
示例#25
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);
        }
示例#26
0
        IEnumerator RecordCR()
        {
            int recRate = 0;
            int namelen = 255;

            System.Text.StringBuilder name = new System.Text.StringBuilder(namelen);
            System.Guid       guid;
            FMOD.SPEAKERMODE  speakermode;
            FMOD.DRIVER_STATE driverstate;
            result = system.getRecordDriverInfo(this.recordDeviceId, name, namelen, out guid, out recRate, out speakermode, out recChannels, out driverstate);
            ERRCHECK(result, "system.getRecordDriverInfo");

            // compensate the input rate for the current output rate
            this.GetComponent <AudioSource>().pitch = ((float)(recRate * recChannels) / (float)(AudioSettings.outputSampleRate * (int)AudioSettings.speakerMode));

            exinfo                  = new FMOD.CREATESOUNDEXINFO();
            exinfo.numchannels      = recChannels;
            exinfo.format           = FMOD.SOUND_FORMAT.PCM16;
            exinfo.defaultfrequency = recRate;
            exinfo.length           = (uint)(recRate * sizeof(short) * recChannels);

            result = system.createSound(string.Empty, FMOD.MODE.LOOP_NORMAL | FMOD.MODE.OPENUSER, ref exinfo, out sound);
            ERRCHECK(result, "system.createSound");

            this.GetComponent <AudioSource>().Play();

            result = system.recordStart(this.recordDeviceId, sound, true);
            ERRCHECK(result, "system.recordStart");

            result = sound.getLength(out soundlength, FMOD.TIMEUNIT.PCM);
            ERRCHECK(result, "sound.getLength");

            this.isRecording = true;

            if (this.OnRecordingStarted != null)
            {
                this.OnRecordingStarted.Invoke(this.gameObjectName);
            }

            for (;;)
            {
                result = system.update();
                ERRCHECK(result, "system.update", false);

                if (this.isPaused)
                {
                    yield return(null);
                }

                uint recordpos = 0;

                system.getRecordPosition(this.recordDeviceId, out recordpos);
                ERRCHECK(result, "system.getRecordPosition");

                if (recordpos != lastrecordpos)
                {
                    int blocklength;

                    blocklength = (int)recordpos - (int)lastrecordpos;
                    if (blocklength < 0)
                    {
                        blocklength += (int)soundlength;
                    }

                    /*
                     * Lock the sound to get access to the raw data.
                     */
                    result = sound.@lock((uint)(lastrecordpos * exinfo.numchannels * 2), (uint)(blocklength * exinfo.numchannels * 2), out ptr1, out ptr2, out len1, out len2);   /* * exinfo.numchannels * 2 = stereo 16bit.  1 sample = 4 bytes. */

                    /*
                     * Write it to output.
                     */
                    if (ptr1.ToInt64() != 0 && len1 > 0)
                    {
                        datalength += len1;
                        byte[] barr = new byte[len1];
                        Marshal.Copy(ptr1, barr, 0, (int)len1);

                        this.AddBytesToOutputBuffer(barr);
                    }
                    if (ptr2.ToInt64() != 0 && len2 > 0)
                    {
                        datalength += len2;
                        byte[] barr = new byte[len2];
                        Marshal.Copy(ptr2, barr, 0, (int)len2);
                        this.AddBytesToOutputBuffer(barr);
                    }

                    /*
                     * Unlock the sound to allow FMOD to use it again.
                     */
                    result = sound.unlock(ptr1, ptr2, len1, len2);
                }

                lastrecordpos = recordpos;

                // print(string.Format("Record buffer pos = {0} : Record time = {1}:{2}", recordpos, datalength / exinfo.defaultfrequency / exinfo.numchannels / 2 / 60, (datalength / exinfo.defaultfrequency / exinfo.numchannels / 2) % 60));

                // System.Threading.Thread.Sleep(10);

                yield return(null);
            }
        }
示例#27
0
        public void Output(int channel, IntPtr buffer, bool block, int volume)
        {
            FMOD.RESULT result;

            Debug.Assert(channel >= 0 && channel <= 7);
            if (this.Channels[channel].Reserved == false)
            {
                return;
            }

            if (this.Channels[channel].Channel != null)
            {
                this.Channels[channel].Channel.stop();
                this.Channels[channel].Channel = null;
            }

            if (this.Channels[channel].Sound != null)
            {
                this.Channels[channel].Sound.release();
                this.Channels[channel].Sound = null;
            }

            uint size = (uint)(this.Channels[channel].SampleCount * 2 * 2);

            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = size;
            exinfo.numchannels = this.Channels[channel].Format == AudioFormat.Mono ? 1 : 2;
            exinfo.defaultfrequency = 44100;
            exinfo.format = FMOD.SOUND_FORMAT.PCM16;
            exinfo.suggestedsoundtype = FMOD.SOUND_TYPE.RAW;

            result = this.AudioSystem.createSound(buffer, FMOD.MODE.OPENMEMORY | FMOD.MODE.OPENRAW | FMOD.MODE.CREATESAMPLE | FMOD.MODE.SOFTWARE | FMOD.MODE._2D, ref exinfo, ref this.Channels[channel].Sound);
            Debug.Assert(result == FMOD.RESULT.OK);
            result = this.AudioSystem.playSound(FMOD.CHANNELINDEX.REUSE, this.Channels[channel].Sound, false, ref this.Channels[channel].Channel);
            Debug.Assert(result == FMOD.RESULT.OK);

            //using (FileStream stream = File.OpenWrite(String.Format("sound_test_{0}.bin", counter++)))
            //using (BinaryWriter writer = new BinaryWriter(stream))
            //{
            //    writer.Write(bytes);
            //}
        }
示例#28
0
        public Sound Load(Stream s)
        {
            byte[] buffer = new byte[s.Length];
            s.Read(buffer, 0, (int)s.Length);

            FMOD.RESULT result;
            FMOD.Sound sound1 = null;
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = (uint)s.Length;

            //result = system.createSound(buffer, (FMOD.MODE.HARDWARE | FMOD.MODE._3D | FMOD.MODE.OPENMEMORY), ref exinfo, ref sound1);
            result = system.createSound(buffer, (FMOD.MODE.HARDWARE | FMOD.MODE._3D | FMOD.MODE.OPENMEMORY | FMOD.MODE._3D_LINEARROLLOFF), ref exinfo, ref sound1);
            ERRCHECK(result);

            sound1.set3DMinMaxDistance(500, 5000);
            return new FmodSound(this, sound1, false);
        }
            ///<summary>
            ///    Initialize a new microphone instance, creating the
            ///    FMOD sound object, optionally opening a recording
            ///    stream, and creating and starting a timer instance
            ///    to copy the PCM samples.
            ///</summary>
            public void InitMicrophone(VoiceParmSet parmSet, bool reconfigure)
            {
                log.DebugFormat(voiceMgr, "MicrophoneChannel.InitMicrophone called with recording WAV({0}), Speex({1})", recordingWAV, recordingSpeex);
                if (channelCodec != null)
                    return;
                try {
                    log.Debug(voiceMgr, "MicrophoneChannel.InitMicrophone: Creating codec");
                    encoderOutputBuffer = new byte[maxBytesPerEncodedFrame];
                    if (voiceMgr.runningVoiceBot) {
                        ApplyVoiceBotParms(parmSet, reconfigure);
                        SetTimeOfNextPlayback();
                    }
                    else {
                        encoderInputBuffer = new short[maxSamplesPerFrame];
                        channelCodec = new SpeexCodec();
                        int encodecFrameSize = channelCodec.InitEncoder(maxSamplesPerFrame, samplesPerFrame, samplesPerSecond);
                        if (encodecFrameSize != samplesPerFrame)
                            log.ErrorFormat(voiceMgr, "MicrophoneChannel.InitMicrophone: The encoder frame size {0} != samplesPerFrame " + samplesPerFrame);
                        ApplyMicrophoneSettings(parmSet, reconfigure);
                        // create a sound object
                        FMOD.RESULT result;
                        FMOD.MODE mode = FMOD.MODE._2D | FMOD.MODE.OPENUSER | FMOD.MODE.SOFTWARE | FMOD.MODE.LOOP_NORMAL;
                        lock(voiceMgr.usingFmod) {
                            FMOD.CREATESOUNDEXINFO  exinfo = new FMOD.CREATESOUNDEXINFO();
                            exinfo.cbsize = Marshal.SizeOf(exinfo);
                            exinfo.decodebuffersize = 0;
                            exinfo.length = (uint)(micQueueSize * 2);
                            exinfo.numchannels = 1;
                            exinfo.defaultfrequency = samplesPerSecond;
                            exinfo.format = FMOD.SOUND_FORMAT.PCM16;

                            log.Debug(voiceMgr, "MicrophoneChannel.InitMicrophone: Creating sound");
                            result = voiceMgr.fmod.createSound((string)null, mode, ref exinfo, ref channelSound);
                        }
                        try {
                            ERRCHECK(result);
                        }
                        catch (Exception e) {
                            log.ErrorFormat(voiceMgr, "MicrophoneChannel.InitMicrophone: Error creating microphone sound: {0}; stack trace\n {1}",
                                e.Message, e.StackTrace);
                        }
                        SetMicDevice();
                        micSamples = new short[micQueueSize];
                        if (recordingWAV || recordingSpeex) {
                            log.Debug(voiceMgr, "MicrophoneChannel.InitMicrophone: Calling StartRecording");
                            StartRecording(channelSound, voiceMgr.LogFolderPath("RecordMic"), recordingWAV, recordingSpeex);
                        }
                        log.Debug(voiceMgr, "MicrophoneChannel.InitMicrophone: Calling StartFmodMicUpdates");
                        StartFmodMicUpdates(channelSound);
                        log.Debug(voiceMgr, "MicrophoneChannel.InitMicrophone: Calling StartChannel");
                        StartChannel(false);
                    }
                    micHandlingTimer = new System.Timers.Timer();
                    micHandlingTimer.Elapsed += MicHandlingTimerTick;
                    micHandlingTimer.Interval = 10; // ms
                    micHandlingTimer.Enabled = true;
                    if (usingDataFrameAggregation) {
                        dataFrameAggregator = new DataFrameAggregator(voiceMgr, deviceNumber, this);
                        dataFrameAggregator.Start();
                    }
                    sourceReady = true;
                }
                catch (Exception e) {
                    log.Error(voiceMgr, "MicrophoneChannel.InitMicrophone: Exception " + e.Message + ", stack trace\n" + e.StackTrace);
                }
            }
示例#30
0
 private static extern FMOD.RESULT FMOD_System_CreateSound(IntPtr systemraw, IntPtr data, FMOD.MODE mode, ref FMOD.CREATESOUNDEXINFO exinfo, ref IntPtr sound);
示例#31
0
        private void PreviewAsset(AssetPreloadData asset)
        {
            switch (asset.Type2)
            {
                #region Texture2D
                case 28: //Texture2D
                    {
                        Texture2D m_Texture2D = new Texture2D(asset, true);
                        
                        if (m_Texture2D.m_TextureFormat < 30)
                        {
                            byte[] imageBuffer = new byte[128 + m_Texture2D.image_data_size];

                            imageBuffer[0] = 0x44;
                            imageBuffer[1] = 0x44;
                            imageBuffer[2] = 0x53;
                            imageBuffer[3] = 0x20;
                            imageBuffer[4] = 0x7c;
                            
                            BitConverter.GetBytes(m_Texture2D.dwFlags).CopyTo(imageBuffer, 8);
                            BitConverter.GetBytes(m_Texture2D.m_Height).CopyTo(imageBuffer, 12);
                            BitConverter.GetBytes(m_Texture2D.m_Width).CopyTo(imageBuffer, 16);
                            BitConverter.GetBytes(m_Texture2D.dwPitchOrLinearSize).CopyTo(imageBuffer, 20);
                            BitConverter.GetBytes(m_Texture2D.dwMipMapCount).CopyTo(imageBuffer, 28);
                            BitConverter.GetBytes(m_Texture2D.dwSize).CopyTo(imageBuffer, 76);
                            BitConverter.GetBytes(m_Texture2D.dwFlags2).CopyTo(imageBuffer, 80);
                            BitConverter.GetBytes(m_Texture2D.dwFourCC).CopyTo(imageBuffer, 84);
                            BitConverter.GetBytes(m_Texture2D.dwRGBBitCount).CopyTo(imageBuffer, 88);
                            BitConverter.GetBytes(m_Texture2D.dwRBitMask).CopyTo(imageBuffer, 92);
                            BitConverter.GetBytes(m_Texture2D.dwGBitMask).CopyTo(imageBuffer, 96);
                            BitConverter.GetBytes(m_Texture2D.dwBBitMask).CopyTo(imageBuffer, 100);
                            BitConverter.GetBytes(m_Texture2D.dwABitMask).CopyTo(imageBuffer, 104);
                            BitConverter.GetBytes(m_Texture2D.dwCaps).CopyTo(imageBuffer, 108);
                            BitConverter.GetBytes(m_Texture2D.dwCaps2).CopyTo(imageBuffer, 112);
                            
                            m_Texture2D.image_data.CopyTo(imageBuffer, 128);

                            imageTexture = DDSDataToBMP(imageBuffer);
                            imageTexture.RotateFlip(RotateFlipType.RotateNoneFlipY);
                            previewPanel.BackgroundImage = imageTexture;
                            previewPanel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
                        }
                        else { StatusStripUpdate("Unsupported image for preview. Try to export."); }
                        break;
                    }
                #endregion
                #region AudioClip
                case 83: //AudioClip
                    {
                        AudioClip m_AudioClip = new AudioClip(asset, true);

                        //MemoryStream memoryStream = new MemoryStream(m_AudioData, true);
                        //System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer(memoryStream);
                        //soundPlayer.Play();

                        FMOD.RESULT result;
                        FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
                        
                        exinfo.cbsize = Marshal.SizeOf(exinfo);
                        exinfo.length = (uint)m_AudioClip.m_Size;

                        result = system.createSound(m_AudioClip.m_AudioData, (FMOD.MODE.OPENMEMORY | loopMode), ref exinfo, out sound);
                        if (ERRCHECK(result)) { break; }

                        result = sound.getLength(out FMODlenms, FMOD.TIMEUNIT.MS);
                        if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE))
                        {
                            if (ERRCHECK(result)) { break; }
                        }

                        result = system.playSound(sound, null, false, out channel);
                        if (ERRCHECK(result)) { break; }

                        timer.Start();
                        FMODstatusLabel.Text = "Playing";
                        FMODpanel.Visible = true;

                        //result = channel.getChannelGroup(out channelGroup);
                        //if (ERRCHECK(result)) { break; }

                        result = channel.getFrequency(out FMODfrequency);
                        ERRCHECK(result);

                        FMODinfoLabel.Text = FMODfrequency.ToString() + " Hz";
                        break;
                    }
                #endregion
                #region Shader & TextAsset
                case 48:
                case 49:
                    {
                        TextAsset m_TextAsset = new TextAsset(asset, true);
                        
                        string m_Script_Text = UnicodeEncoding.UTF8.GetString(m_TextAsset.m_Script);
                        m_Script_Text = Regex.Replace(m_Script_Text, "(?<!\r)\n", "\r\n");
                        textPreviewBox.Text = m_Script_Text;
                        textPreviewBox.Visible = true;

                        break;
                    }
                #endregion
                #region Font
                case 128: //Font
                    {
                        unityFont m_Font = new unityFont(asset);
                        
                        if (m_Font.extension != ".otf" && m_Font.m_FontData != null)
                        {
                            IntPtr data = Marshal.AllocCoTaskMem(m_Font.m_FontData.Length);
                            Marshal.Copy(m_Font.m_FontData, 0, data, m_Font.m_FontData.Length);

                            System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
                            // We HAVE to do this to register the font to the system (Weird .NET bug !)
                            uint cFonts = 0;
                            AddFontMemResourceEx(data, (uint)m_Font.m_FontData.Length, IntPtr.Zero, ref cFonts);

                            pfc.AddMemoryFont(data, m_Font.m_FontData.Length);
                            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(data);

                            //textPreviewBox.Font = new Font(pfc.Families[0], 16, FontStyle.Regular);
                            //textPreviewBox.Text = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWYZ\r\n1234567890.:,;'\"(!?)+-*/=\r\nThe quick brown fox jumps over the lazy dog. 1234567890";
                            fontPreviewBox.SelectionStart = 0;
                            fontPreviewBox.SelectionLength = 80;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 16, FontStyle.Regular);
                            fontPreviewBox.SelectionStart = 81;
                            fontPreviewBox.SelectionLength = 56;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 12, FontStyle.Regular);
                            fontPreviewBox.SelectionStart = 138;
                            fontPreviewBox.SelectionLength = 56;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 18, FontStyle.Regular);
                            fontPreviewBox.SelectionStart = 195;
                            fontPreviewBox.SelectionLength = 56;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 24, FontStyle.Regular);
                            fontPreviewBox.SelectionStart = 252;
                            fontPreviewBox.SelectionLength = 56;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 36, FontStyle.Regular);
                            fontPreviewBox.SelectionStart = 309;
                            fontPreviewBox.SelectionLength = 56;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 48, FontStyle.Regular);
                            fontPreviewBox.SelectionStart = 366;
                            fontPreviewBox.SelectionLength = 56;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 60, FontStyle.Regular);
                            fontPreviewBox.SelectionStart = 423;
                            fontPreviewBox.SelectionLength = 55;
                            fontPreviewBox.SelectionFont = new Font(pfc.Families[0], 72, FontStyle.Regular);
                            fontPreviewBox.Visible = true;
                        }
                        else { StatusStripUpdate("Unsupported font for preview. Try to export."); }

                        break;
                    }
                #endregion
            }
        }
示例#32
0
        IEnumerator PlayCR()
        {
            var _url = this.url;

            this.playlistType = null;

            if (this.url.EndsWith("pls", System.StringComparison.OrdinalIgnoreCase))
            {
                this.playlistType = PlaylistType.PLS;
            }
            else if (this.url.EndsWith("m3u", System.StringComparison.OrdinalIgnoreCase))
            {
                this.playlistType = PlaylistType.M3U;
            }
            else if (this.url.EndsWith("m3u8", System.StringComparison.OrdinalIgnoreCase))
            {
                this.playlistType = PlaylistType.M3U8;
            }

            if (this.playlistType.HasValue)
            {
                string playlist = string.Empty;

                // allow local playlist
                if (!this.url.StartsWith("http", System.StringComparison.OrdinalIgnoreCase) && !this.url.StartsWith("file", System.StringComparison.OrdinalIgnoreCase))
                {
                    this.url = "file://" + this.url;
                }

                /*
                 * UnityWebRequest introduced in 5.2, but WWW still worked on standalone/mobile
                 * However, in 5.3 is WWW hardcoded to Abort() on iOS on non secure requests - which is likely a bug - so from 5.3 on we require UnityWebRequest
                 */
#if UNITY_5_3_OR_NEWER
#if UNITY_5_3
                using (UnityEngine.Experimental.Networking.UnityWebRequest www = UnityEngine.Experimental.Networking.UnityWebRequest.Get(this.url))
#else
                using (UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get(this.url))
#endif
                {
                    yield return(www.Send());

                    if (www.isError || !string.IsNullOrEmpty(www.error))
                    {
                        var msg = string.Format("Can't read playlist from {0} - {1}", this.url, www.error);

                        LOG(LogLevel.ERROR, msg);

                        if (this.OnError != null)
                        {
                            this.OnError.Invoke(this.gameObjectName, msg);
                        }

                        throw new System.Exception(msg);
                    }

                    playlist = www.downloadHandler.text;
                }
#else
                using (WWW www = new WWW(this.url))
                {
                    yield return(www);

                    if (!string.IsNullOrEmpty(www.error))
                    {
                        var msg = string.Format("Can't read playlist from {0} - {1}", this.url, www.error);

                        LOG(LogLevel.ERROR, msg);

                        if (this.OnError != null)
                        {
                            this.OnError.Invoke(this.gameObjectName, msg);
                        }

                        throw new System.Exception(msg);
                    }

                    playlist = www.text;
                }
#endif

                if (this.playlistType.Value == PlaylistType.M3U ||
                    this.playlistType.Value == PlaylistType.M3U8)
                {
                    _url = this.URLFromM3UPlaylist(playlist);
                    LOG(LogLevel.INFO, "URL from M3U/8 playlist: {0}", _url);
                }
                else
                {
                    _url = this.URLFromPLSPlaylist(playlist);
                    LOG(LogLevel.INFO, "URL from PLS playlist: {0}", _url);
                }

                if (string.IsNullOrEmpty(_url))
                {
                    var msg = string.Format("Can't parse playlist {0}", this.url);

                    LOG(LogLevel.ERROR, msg);

                    if (this.OnError != null)
                    {
                        this.OnError.Invoke(this.gameObjectName, msg);
                    }

                    throw new System.Exception(msg);
                }

                // allow FMOD to stream locally
                if (_url.StartsWith("file://", System.StringComparison.OrdinalIgnoreCase))
                {
                    _url = _url.Substring(7);
                }
            }

            /*
             * pass empty / default CREATESOUNDEXINFO, otherwise it hits nomarshalable unmanaged structure path on IL2CPP
             */
            var extInfo = new FMOD.CREATESOUNDEXINFO();
            // must be hinted on iOS due to ERR_FILE_COULDNOTSEEK on getOpenState
            // allow any type for local files
            switch (this.streamType)
            {
            case StreamAudioType.MPEG:
                extInfo.suggestedsoundtype = FMOD.SOUND_TYPE.MPEG;
                break;

            case StreamAudioType.OGGVORBIS:
                extInfo.suggestedsoundtype = FMOD.SOUND_TYPE.OGGVORBIS;
                break;

            case StreamAudioType.WAV:
                extInfo.suggestedsoundtype = FMOD.SOUND_TYPE.WAV;
                break;

            case StreamAudioType.RAW:
                extInfo.suggestedsoundtype = FMOD.SOUND_TYPE.RAW;
                break;

            default:
                extInfo.suggestedsoundtype = FMOD.SOUND_TYPE.UNKNOWN;
                break;
            }

            /*
             * opening flags for streaming createSound
             */
            var flags = FMOD.MODE.CREATESTREAM
                        | FMOD.MODE.NONBLOCKING
                        | FMOD.MODE.IGNORETAGS
                        | FMOD.MODE.MPEGSEARCH
                        | FMOD.MODE.OPENONLY
            ;

            if (this.streamType == StreamAudioType.RAW)
            {
                // raw data needs to ignore audio format and
                // Use FMOD_CREATESOUNDEXINFO to specify format.Requires at least defaultfrequency, numchannels and format to be specified before it will open.Must be little endian data.

                flags |= FMOD.MODE.OPENRAW;

                extInfo.format           = this.RAWSoundFormat;
                extInfo.defaultfrequency = this.RAWFrequency;
                extInfo.numchannels      = this.RAWChannels;
            }

            result = system.createSound(_url
                                        , flags
                                        , ref extInfo
                                        , out sound);
            ERRCHECK(result, "system.createSound");


            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                LOG(LogLevel.INFO, "Setting playback output to speaker...");
                //iOSSpeaker.RouteForPlayback();
                iOSSpeaker.RouteToSpeaker();
            }

            LOG(LogLevel.INFO, "About to play...");

            StartCoroutine(this.StreamCR());
        }
示例#33
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            FMOD.RESULT            result;
            uint                   version = 0;

            /*
                Create a System object and initialize.
            */
            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);

            /*
                Set up the FMOD_CREATESOUNDEXINFO structure for the user stream with room for 2 subsounds. (our subsound double buffer)
            */

            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.defaultfrequency = 44100;
            exinfo.numsubsounds = 2;
            exinfo.numchannels = 1;
            exinfo.format = FMOD.SOUND_FORMAT.PCM16;

            /*
                Create the 'parent' stream that contains the substreams.  Set it to loop so that it loops between subsound 0 and 1.
            */
            result = system.createStream("", FMOD.MODE.LOOP_NORMAL | FMOD.MODE.OPENUSER, ref exinfo, ref sound);
            ERRCHECK(result);

            /*
                Add 2 of our streams as children of the parent.  They should be the same format (ie mono/stereo and bitdepth) as the parent sound.
                When subsound 0 has finished and it is playing subsound 1, we will swap subsound 0 with a new sound, and the same for when subsound 1 has finished,
                causing a continual double buffered flip, which means continuous sound.
            */
            result = system.createStream(soundname[0], FMOD.MODE.DEFAULT, ref subsound[0]);
            ERRCHECK(result);

            result = system.createStream(soundname[1], FMOD.MODE.DEFAULT, ref subsound[1]);
            ERRCHECK(result);

            result = sound.setSubSound(0, subsound[0]);
            ERRCHECK(result);

            result = sound.setSubSound(1, subsound[1]);
            ERRCHECK(result);

            /*
                Set up the gapless sentence to contain these first 2 streams.
            */
            {
                int[] soundlist = { 0, 1 };

                result = sound.setSubSoundSentence(soundlist, 2);
                ERRCHECK(result);
            }

            subsoundid = 0;
            sentenceid = 2;     /* The next sound to be appeneded to the stream. */

            /*
                Play the sound.
            */

            result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel);
            ERRCHECK(result);
        }
示例#34
0
 private static extern FMOD.RESULT FMOD_System_CreateStream(IntPtr systemraw, short[] data, FMOD.MODE mode, ref FMOD.CREATESOUNDEXINFO exinfo, ref IntPtr stream);
示例#35
0
        public static bool ExportAudioClip(AssetPreloadData asset, string exportPath)
        {
            var m_AudioClip = new AudioClip(asset, true);

            if (m_AudioClip.m_AudioData == null)
            {
                return(false);
            }
            var convertAudio = (bool)Properties.Settings.Default["convertAudio"];

            if (convertAudio && m_AudioClip.IsFMODSupport)
            {
                var exportFullName = exportPath + asset.Text + ".wav";
                if (ExportFileExists(exportFullName))
                {
                    return(false);
                }
                FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
                var result = FMOD.Factory.System_Create(out var system);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                result = system.init(1, FMOD.INITFLAGS.NORMAL, IntPtr.Zero);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                exinfo.cbsize = Marshal.SizeOf(exinfo);
                exinfo.length = (uint)m_AudioClip.m_Size;
                result        = system.createSound(m_AudioClip.m_AudioData, FMOD.MODE.OPENMEMORY, ref exinfo, out var sound);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                result = sound.getSubSound(0, out var subsound);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                result = subsound.getFormat(out var type, out var format, out int NumChannels, out int BitsPerSample);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                result = subsound.getDefaults(out var frequency, out int priority);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                var SampleRate = (int)frequency;
                result = subsound.getLength(out var length, FMOD.TIMEUNIT.PCMBYTES);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                result = subsound.@lock(0, length, out var ptr1, out var ptr2, out var len1, out var len2);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                byte[] buffer = new byte[len1 + 44];
                //添加wav头
                Encoding.UTF8.GetBytes("RIFF").CopyTo(buffer, 0);
                BitConverter.GetBytes(len1 + 36).CopyTo(buffer, 4);
                Encoding.UTF8.GetBytes("WAVEfmt ").CopyTo(buffer, 8);
                BitConverter.GetBytes(16).CopyTo(buffer, 16);
                BitConverter.GetBytes((short)1).CopyTo(buffer, 20);
                BitConverter.GetBytes((short)NumChannels).CopyTo(buffer, 22);
                BitConverter.GetBytes(SampleRate).CopyTo(buffer, 24);
                BitConverter.GetBytes(SampleRate * NumChannels * BitsPerSample / 8).CopyTo(buffer, 28);
                BitConverter.GetBytes((short)(NumChannels * BitsPerSample / 8)).CopyTo(buffer, 32);
                BitConverter.GetBytes((short)BitsPerSample).CopyTo(buffer, 34);
                Encoding.UTF8.GetBytes("data").CopyTo(buffer, 36);
                BitConverter.GetBytes(len1).CopyTo(buffer, 40);
                Marshal.Copy(ptr1, buffer, 44, (int)len1);
                File.WriteAllBytes(exportFullName, buffer);
                result = subsound.unlock(ptr1, ptr2, len1, len2);
                if (result != FMOD.RESULT.OK)
                {
                    return(false);
                }
                subsound.release();
                sound.release();
                system.release();
            }
            else
            {
                var exportFullName = exportPath + asset.Text + asset.extension;
                if (ExportFileExists(exportFullName))
                {
                    return(false);
                }
                File.WriteAllBytes(exportFullName, m_AudioClip.m_AudioData);
            }
            return(true);
        }
示例#36
0
        public byte[] ConvertToWav()
        {
            var m_AudioData = m_AudioClip.m_AudioData.GetData();

            if (m_AudioData == null || m_AudioData.Length == 0)
            {
                return(null);
            }
            var exinfo = new FMOD.CREATESOUNDEXINFO();
            var result = FMOD.Factory.System_Create(out var system);

            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            result = system.init(1, FMOD.INITFLAGS.NORMAL, IntPtr.Zero);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            exinfo.cbsize = Marshal.SizeOf(exinfo);
            exinfo.length = (uint)m_AudioClip.m_Size;
            result        = system.createSound(m_AudioData, FMOD.MODE.OPENMEMORY, ref exinfo, out var sound);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            result = sound.getSubSound(0, out var subsound);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            result = subsound.getFormat(out var type, out var format, out int channels, out int bits);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            result = subsound.getDefaults(out var frequency, out int priority);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            var sampleRate = (int)frequency;

            result = subsound.getLength(out var length, FMOD.TIMEUNIT.PCMBYTES);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            result = subsound.@lock(0, length, out var ptr1, out var ptr2, out var len1, out var len2);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            byte[] buffer = new byte[len1 + 44];
            //添加wav头
            Encoding.UTF8.GetBytes("RIFF").CopyTo(buffer, 0);
            BitConverter.GetBytes(len1 + 36).CopyTo(buffer, 4);
            Encoding.UTF8.GetBytes("WAVEfmt ").CopyTo(buffer, 8);
            BitConverter.GetBytes(16).CopyTo(buffer, 16);
            BitConverter.GetBytes((short)1).CopyTo(buffer, 20);
            BitConverter.GetBytes((short)channels).CopyTo(buffer, 22);
            BitConverter.GetBytes(sampleRate).CopyTo(buffer, 24);
            BitConverter.GetBytes(sampleRate * channels * bits / 8).CopyTo(buffer, 28);
            BitConverter.GetBytes((short)(channels * bits / 8)).CopyTo(buffer, 32);
            BitConverter.GetBytes((short)bits).CopyTo(buffer, 34);
            Encoding.UTF8.GetBytes("data").CopyTo(buffer, 36);
            BitConverter.GetBytes(len1).CopyTo(buffer, 40);
            Marshal.Copy(ptr1, buffer, 44, (int)len1);
            result = subsound.unlock(ptr1, ptr2, len1, len2);
            if (result != FMOD.RESULT.OK)
            {
                return(null);
            }
            subsound.release();
            sound.release();
            system.release();
            return(buffer);
        }
示例#37
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);
        }
 ///<summary>
 ///    Create the FMOD sound associated with the channel,
 ///    and if this channel will be recorded, start the
 ///    recording. 
 ///</summary>
 public void ActivateChannel()
 {
     if (sourceActive) {
         log.ErrorFormat(voiceMgr, "VoiceChannel.ActivateChannel, channel {0}/FMOD{1}, channel already active", voiceNumber);
         return;
     }
     try {
         log.Debug(voiceMgr, "VoiceChannel.ActivateChannel: Creating codec");
         channelCodec.InitDecoder(true, samplesPerFrame, samplesPerFrame);
         FMOD.RESULT result;
         lock(voiceMgr.usingFmod) {
             FMOD.MODE twoOrThree = (positionalSound ? FMOD.MODE._3D : FMOD.MODE._2D);
             FMOD.MODE mode = (twoOrThree | FMOD.MODE.OPENUSER | FMOD.MODE.LOOP_NORMAL | FMOD.MODE.HARDWARE | FMOD.MODE.CREATESTREAM);
             FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
             exinfo.cbsize = Marshal.SizeOf(exinfo);
             exinfo.decodebuffersize = (uint)(samplesPerFrame * 2 * 2);
             exinfo.length = (uint)samplesPerFrame * 2;
             exinfo.numchannels = 1;
             exinfo.defaultfrequency = samplesPerSecond;
             exinfo.format = FMOD.SOUND_FORMAT.PCM16;
             exinfo.pcmreadcallback = voiceReadCallback;
             log.Debug(voiceMgr, "VoiceChannel.ActivateChannel: Creating sound");
             result = voiceMgr.fmod.createSound((string)null, mode, ref exinfo, ref channelSound);
         }
         ERRCHECK(result);
         if (recordingWAV || recordingSpeex) {
             if (!voiceMgr.recordedOids.Contains(oid)) {
                 File.Delete(voiceMgr.LogFolderPath("RecordVoice-" + oid + ".wav"));
                 File.Delete(voiceMgr.LogFolderPath("RecordVoice-" + oid + ".speex"));
                 voiceMgr.recordedOids.Add(oid);
             }
             StartRecording(channelSound, voiceMgr.LogFolderPath("RecordVoice-" + oid), recordingWAV, recordingSpeex);
         }
         log.Debug(voiceMgr, "VoiceChannel.ActivateChannel: Calling StartChannel");
         StartChannel(true);
     }
     catch (Exception e) {
         log.ErrorFormat(voiceMgr, "VoiceChannel.ActivateChannel: Error activating channel {0}; exception : {1}", voiceNumber, e.Message);
     }
 }