public void Update(GameTime gameTime) { system.update(); if (IsSongPlaying()) { uint length = 0; uint position = 0; CurrentSong.getLength(out length, FMOD.TIMEUNIT.MS); Channel.getPosition(out position, FMOD.TIMEUNIT.MS); if (position == length) { NextSongEvent.Invoke(); } } #region Update System & FFT Algorithm if (FFTEnabled) { // Perform a Fast Fourier Transform int windowSize = spectrum.Length; //Samples. IntPtr data; uint length; //hanning bpm MyDSP.setParameterInt((int)FMOD.DSP_FFT.WINDOWTYPE, (int)FMOD.DSP_FFT_WINDOW.HAMMING); MyDSP.setParameterInt((int)FMOD.DSP_FFT.WINDOWSIZE, windowSize); MyDSP.getParameterData((int)FMOD.DSP_FFT.SPECTRUMDATA, out data, out length); MyDSP.getParameterFloat((int)FMOD.DSP_FFT.DOMINANT_FREQ, out higher_freq); fftParameter = (FMOD.DSP_PARAMETER_FFT)Marshal.PtrToStructure(data, typeof(FMOD.DSP_PARAMETER_FFT)); #region BPMDetection if (fftParameter.spectrum.Length != 0) { for (int i = 0; i < windowSize; i++) { if (fftParameter.spectrum.Length == 2) { spectrum[i] = (fftParameter.spectrum[0][i] + fftParameter.spectrum[1][i]) / 2f; } } } previousSpectrum = spectrum; #endregion } #endregion }
void createFMODSound(string fn) { // load the _sound FMOD.RESULT r; r = MusicEngine.AudioEngine.createSound(fn, FMOD.MODE.SOFTWARE, ref _sound); if (Util.ERRCHECK(r)) { throw new ContentLoadException(Util.ERRMSG(r)); } else { if (_sound != null) { r = _sound.setMode(FMOD.MODE.LOOP_NORMAL); // enable loop functionality, Util.ERRCHECK(r); r = _sound.setLoopCount(0); // but do not loop by default Util.ERRCHECK(r); // determine sample duration uint l = 0; r = _sound.getLength(ref l, FMOD.TIMEUNIT.MS); if (!Util.ERRCHECK(r)) { _soundDuration = ((double)l) / 1000.0; } } else { Util.Log("AudioSample.createFMODSound(): Error, _sound is null."); } } }
private void start_Click(object sender, System.EventArgs e) { FMOD.RESULT result; result = system.recordStart(selected, sound, true); ERRCHECK(result); soundlength = 0; lastrecordpos = 0; datalength = 0; fs = new FileStream("record.wav", FileMode.Create, FileAccess.Write); /* * Write out the wav header. As we don't know the length yet it will be 0. */ WriteWavHeader(0); recording = true; result = sound.getLength(ref soundlength, FMOD.TIMEUNIT.PCM); ERRCHECK(result); start.Enabled = false; }
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
/// <summary> /// Gets the length of the media in milliseconds /// </summary> /// <param name="media"></param> /// <returns></returns> private uint GetLength() { FMOD.RESULT result; uint length; //get length result = _sound.getLength(out length, FMOD.TIMEUNIT.MS); CheckError(result); return(length); }
public static uint GetPlayTime() { if (sound == null) { return(0); } uint length = 0; sound.getLength(ref length, FMOD.TIMEUNIT.MS); return(length); }
private void timer_Tick(object sender, System.EventArgs e) { FMOD.RESULT result; uint ms = 0; uint lenms = 0; bool paused = false; bool playing = false; int channelsplaying = 0; if (channel != null) { FMOD.Sound currentsound = null; result = channel.isPlaying(ref playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE) && (result != FMOD.RESULT.ERR_CHANNEL_STOLEN)) { ERRCHECK(result); } result = channel.getPaused(ref paused); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE) && (result != FMOD.RESULT.ERR_CHANNEL_STOLEN)) { ERRCHECK(result); } result = channel.getPosition(ref ms, FMOD.TIMEUNIT.MS); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE) && (result != FMOD.RESULT.ERR_CHANNEL_STOLEN)) { ERRCHECK(result); } channel.getCurrentSound(ref currentsound); if (currentsound != null) { result = currentsound.getLength(ref lenms, FMOD.TIMEUNIT.MS); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE) && (result != FMOD.RESULT.ERR_CHANNEL_STOLEN)) { ERRCHECK(result); } } system.getChannelsPlaying(ref channelsplaying); } statusBar.Text = "Time " + (ms / 1000 / 60) + ":" + (ms / 1000 % 60) + ":" + (ms / 10 % 100) + "/" + (lenms / 1000 / 60) + ":" + (lenms / 1000 % 60) + ":" + (lenms / 10 % 100) + " " + (paused ? "Paused " : playing ? "Playing" : "Stopped") + " Channels Playing " + channelsplaying; if (system != null) { system.update(); } }
public void CheckPlaylist() { if (IsBGMPlaying) { uint len = 0, pos = 0; SoundBGM.getLength(ref len, FMOD.TIMEUNIT.MS); ChannelBGM.getPosition(ref pos, FMOD.TIMEUNIT.MS); if (len == pos) { NextBGM(); } } }
public static int GetLengthOfSoundfile(string filename) { FMOD.Sound sound = null; FMOD.RESULT res = SoundEngine.Instance.system.createStream(filename, FMOD.MODE.OPENONLY, ref sound); uint length = 0; if (sound != null) { sound.getLength(ref length, FMOD.TIMEUNIT.MS); sound.release(); return((int)length); } return(0); }
private void timer_Tick(object sender, System.EventArgs e) { FMOD.RESULT result; uint ms = 0; uint lenms = 0; uint lenmscd = 0; bool playing = false; bool paused = false; if (channel != null) { result = channel.getPaused(ref paused); ERRCHECK(result); result = channel.isPlaying(ref playing); ERRCHECK(result); result = channel.getPosition(ref ms, FMOD.TIMEUNIT.MS); ERRCHECK(result); result = sound.getLength(ref lenms, FMOD.TIMEUNIT.MS); ERRCHECK(result); } if (cdsound != null) { /* * Get length of entire CD. Did you know you can also play 'cdsound' and it will play the whole CD without gaps? */ result = cdsound.getLength(ref lenmscd, FMOD.TIMEUNIT.MS); ERRCHECK(result); } statusBar.Text = "Total CD length: " + (lenmscd / 1000 / 60) + ":" + (lenmscd / 1000 % 60) + ":" + (lenmscd / 10 % 100) + " Track " + (currenttrack + 1) + "/" + numtracks + " : " + (ms / 1000 / 60) + ":" + (ms / 1000 % 60) + ":" + (ms / 10 % 100) + "/" + (lenms / 1000 / 60) + ":" + (lenms / 1000 % 60) + ":" + (lenms / 10 % 100) + (paused ? " Paused " : playing ? " Playing" : " Stopped"); if (system != null) { system.update(); } }
protected override void Open(string fileName) { if (!m_bOpened) { string path = ProjectDoc.Instance.ResourceGroups[ResourceKind.音频].RootPath; RefFMODSound = ((SoundPlayer_FMOD)m_HostPlayer).GetSoundInstance(path + fileName); if (RefFMODSound == null) { return; } uint length = 0; if (ERRCHECK(RefFMODSound.getLength(ref length, FMOD.TIMEUNIT.MS))) { m_nLength = (ulong)length; } else { m_nLength = 0; } m_bOpened = true; } }
public static SoundFileInformation GetSoundFileInformation(string filename) { SoundFileInformation sfInfo = new SoundFileInformation(); try { if (string.IsNullOrEmpty(filename) || !File.Exists(filename)) { return(sfInfo); } ID3Info id3Info = new ID3Info(filename, true); int id3Version = Settings.Current.UseID3Version; if (id3Info.ID3v1Info != null && id3Info.ID3v1Info.HaveTag && id3Version != 1) { sfInfo.Artist = id3Info.ID3v1Info.Artist.Trim(); sfInfo.Title = id3Info.ID3v1Info.Title.Trim(); sfInfo.Comment = id3Info.ID3v1Info.Comment.Trim(); sfInfo.Album = id3Info.ID3v1Info.Album.Trim(); sfInfo.Year = id3Info.ID3v1Info.Year.Trim(); sfInfo.Genre = MapID3GenreToHitbaseGenre(id3Info.ID3v1Info.Genre); sfInfo.TrackNumber = id3Info.ID3v1Info.TrackNumber; sfInfo.ID3Version = 1; } if (id3Info.ID3v2Info != null && id3Info.ID3v2Info.HaveTag && id3Version != 0) { sfInfo.Artist = id3Info.ID3v2Info.GetTextFrame("TPE1").Trim(); sfInfo.Title = id3Info.ID3v2Info.GetTextFrame("TIT2").Trim(); sfInfo.Comment = id3Info.ID3v2Info.GetTextFrame("COMM").Trim(); sfInfo.Album = id3Info.ID3v2Info.GetTextFrame("TALB").Trim(); sfInfo.Year = id3Info.ID3v2Info.GetTextFrame("TYER").Trim(); String trackNumber = id3Info.ID3v2Info.GetTextFrame("TRCK"); sfInfo.TrackNumber = Misc.Atoi(trackNumber); sfInfo.Genre = id3Info.ID3v2Info.GetTextFrame("TCON").Trim(); sfInfo.Composer = id3Info.ID3v2Info.GetTextFrame("TCOM").Trim(); sfInfo.Language = id3Info.ID3v2Info.GetTextFrame("TLAN").Trim(); // Das mit dem Rating geht irgendwie anders. Erst mal raus //string rating = id3Info.ID3v2Info.GetTextFrame("POPM").Trim(); //sfInfo.Rating = Misc.Atoi(rating); string bpm = id3Info.ID3v2Info.GetTextFrame("TBPM").Trim(); sfInfo.BPM = Misc.Atoi(bpm); string length = id3Info.ID3v2Info.GetTextFrame("TLEN"); if (Misc.Atoi(length) > 0) { sfInfo.Length = Misc.Atoi(length); } sfInfo.Images = new List <byte[]>(); if (id3Info.ID3v2Info.AttachedPictureFrames.Items.Length > 0) { ID3.ID3v2Frames.BinaryFrames.BinaryFrame binaryFrame = id3Info.ID3v2Info.AttachedPictureFrames.Items[0]; foreach (AttachedPictureFrame apf in id3Info.ID3v2Info.AttachedPictureFrames.Items) { sfInfo.Images.Add(apf.Data.ToArray()); } } sfInfo.ID3Version = 2; } if (sfInfo.Length == 0) { FMOD.Sound sound = null; FMOD.RESULT res = SoundEngine.FMODSystem.createStream(filename, FMOD.MODE.OPENONLY, ref sound); uint length = 0; if (sound != null) { sound.getLength(ref length, FMOD.TIMEUNIT.MS); sound.release(); sfInfo.Length = (int)length; } } } catch { // Zuerst mal hier alle Fehler ignorieren. } return(sfInfo); }
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); } }
/// <summary> /// Konvertieren von von Sound Dateien zu WAVE mit PCM Header /// </summary> /// <param name="src">Kompletter Pfad zur Quell Datei</param> /// <param name="dest">Kompletter Pfad zur Ziel Datei</param> /// <returns></returns> public bool ConvertToWAVE(string src_file, string dest_file, ConvertToWaveProgressDelegate convertToWaveProgressDelegate) { uint version = 0; FMOD.RESULT result; const int CHUNKSIZE = 262144; FMOD.System system = null; FMOD.Sound sound = null; /* * Global Settings */ result = FMOD.Factory.System_Create(ref system); if (result != FMOD.RESULT.OK) { return(false); } 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") + "."); return(false); } result = system.init(1, FMOD.INITFLAGS.NORMAL, (IntPtr)null); ERRCHECK(result); result = system.createSound(src_file, FMOD.MODE.OPENONLY | FMOD.MODE.ACCURATETIME, ref sound); if (result != FMOD.RESULT.OK) { return(false); } /* * Decode the sound and write it to a .raw file. */ IntPtr data = Marshal.AllocHGlobal(CHUNKSIZE); byte[] buffer = new byte[CHUNKSIZE]; uint length = 0, read = 0; uint bytesread = 0; FileStream fs = new FileStream(dest_file, FileMode.Create, FileAccess.Write); result = sound.getLength(ref length, FMOD.TIMEUNIT.PCMBYTES); ERRCHECK(result); bytesread = 0; do { result = sound.readData(data, CHUNKSIZE, ref read); Marshal.Copy(data, buffer, 0, CHUNKSIZE); fs.Write(buffer, 0, (int)read); bytesread += read; double percent = 100.0 / (double)length * (double)bytesread; convertToWaveProgressDelegate(src_file, dest_file, percent); System.Windows.Forms.Application.DoEvents(); //statusBar.Text = "writing " + bytesread + " bytes of " + length + " to output.raw"; }while (result == FMOD.RESULT.OK && read == CHUNKSIZE); //statusBar.Text = "done"; /* * Loop terminates when either * 1. the read function returns an error. (ie FMOD_ERR_FILE_EOF etc). * 2. the amount requested was different to the amount returned. (somehow got an EOF without the file error, maybe a non stream file format like mod/s3m/xm/it/midi). * * If 'bytesread' is bigger than 'length' then it just means that FMOD miscalculated the size, * but this will not usually happen if FMOD_ACCURATETIME is used. (this will give the correct length for VBR formats) */ fs.Close(); /* * Shut down */ if (sound != null) { result = sound.release(); ERRCHECK(result); } if (system != null) { result = system.close(); ERRCHECK(result); result = system.release(); ERRCHECK(result); } return(true); }
private float BPMDetection(string filename) { float bpm = 0.0f; const int CHUNKSIZE = 4096; FMOD.RESULT result; FMOD.System systemBpm = null; FMOD.Sound soundBpm = null; // Create a System object and initialize. result = FMOD.Factory.System_Create(ref systemBpm); ERRCHECK(result); // Zuerst in eine WAVE-Umwandeln result = systemBpm.init(1, FMOD.INITFLAGS.NORMAL, (IntPtr)null); ERRCHECK(result); result = systemBpm.createSound(filename, FMOD.MODE.OPENONLY | FMOD.MODE.ACCURATETIME, ref soundBpm); ERRCHECK(result); /* * Decode the sound and write it to a .raw file. */ { IntPtr data = Marshal.AllocHGlobal(CHUNKSIZE); byte[] buffer = new byte[CHUNKSIZE]; uint length = 0, read = 0; uint bytesread = 0; MemoryStream memStream = new MemoryStream(); result = soundBpm.getLength(ref length, FMOD.TIMEUNIT.PCMBYTES); ERRCHECK(result); bytesread = 0; do { result = soundBpm.readData(data, CHUNKSIZE, ref read); Marshal.Copy(data, buffer, 0, CHUNKSIZE); memStream.Write(buffer, 0, (int)read); bytesread += read; }while (result == FMOD.RESULT.OK && read == CHUNKSIZE); /* * Loop terminates when either * 1. the read function returns an error. (ie FMOD_ERR_FILE_EOF etc). * 2. the amount requested was different to the amount returned. (somehow got an EOF without the file error, maybe a non stream file format like mod/s3m/xm/it/midi). * * If 'bytesread' is bigger than 'length' then it just means that FMOD miscalculated the size, * but this will not usually happen if FMOD_ACCURATETIME is used. (this will give the correct length for VBR formats) */ memStream.Close(); // In float umwandeln byte[] samples = memStream.ToArray(); float[] floatSamples = new float[samples.Length / 2]; //for (int i = 0; i < samples.Length; i += 4) for (int i = samples.Length / 4; i < samples.Length * 3 / 4; i += 4) { short sampleLeft = BitConverter.ToInt16(samples, i); short sampleRight = BitConverter.ToInt16(samples, i + 2); floatSamples[i / 2] = (float)sampleLeft / 32768.0f; floatSamples[i / 2 + 1] = (float)sampleRight / 32768.0f; } BigMansStuff.PracticeSharp.Core.SoundTouchSharp soundTouch = new BigMansStuff.PracticeSharp.Core.SoundTouchSharp(); bpm = soundTouch.DetectBPM(2, 44100, floatSamples, floatSamples.Length); /* * Shut down */ if (soundBpm != null) { result = soundBpm.release(); ERRCHECK(result); } if (systemBpm != null) { result = systemBpm.close(); ERRCHECK(result); result = systemBpm.release(); ERRCHECK(result); } } return(bpm); }
private void SaveToWav() { FileStream fs = null; int channels = 0, bits = 0; float rate = 0; IntPtr ptr1 = new IntPtr(), ptr2 = new IntPtr(); uint lenbytes = 0, len1 = 0, len2 = 0; FMOD.SOUND_TYPE type = FMOD.SOUND_TYPE.WAV; FMOD.SOUND_FORMAT format = FMOD.SOUND_FORMAT.NONE; int temp1 = 0; float temp3 = 0; if (sound == null) { return; } sound.getFormat(ref type, ref format, ref channels, ref bits); sound.getDefaults(ref rate, ref temp3, ref temp3, ref temp1); sound.getLength(ref lenbytes, FMOD.TIMEUNIT.PCMBYTES); FmtChunk fmtChunk = new FmtChunk(); DataChunk dataChunk = new DataChunk(); WavHeader wavHeader = new WavHeader(); RiffChunk riffChunk = new RiffChunk(); fmtChunk.chunk = new RiffChunk(); fmtChunk.chunk.id = new char[4]; fmtChunk.chunk.id[0] = 'f'; fmtChunk.chunk.id[1] = 'm'; fmtChunk.chunk.id[2] = 't'; fmtChunk.chunk.id[3] = ' '; fmtChunk.chunk.size = Marshal.SizeOf(fmtChunk) - Marshal.SizeOf(riffChunk); fmtChunk.wFormatTag = 1; fmtChunk.nChannels = (ushort)channels; fmtChunk.nSamplesPerSec = (uint)rate; fmtChunk.nAvgBytesPerSec = (uint)(rate * channels * bits / 8); fmtChunk.nBlockAlign = (ushort)(1 * channels * bits / 8); fmtChunk.wBitsPerSample = (ushort)bits; dataChunk.chunk = new RiffChunk(); dataChunk.chunk.id = new char[4]; dataChunk.chunk.id[0] = 'd'; dataChunk.chunk.id[1] = 'a'; dataChunk.chunk.id[2] = 't'; dataChunk.chunk.id[3] = 'a'; dataChunk.chunk.size = (int)lenbytes; wavHeader.chunk = new RiffChunk(); wavHeader.chunk.id = new char[4]; wavHeader.chunk.id[0] = 'R'; wavHeader.chunk.id[1] = 'I'; wavHeader.chunk.id[2] = 'F'; wavHeader.chunk.id[3] = 'F'; wavHeader.chunk.size = (int)(Marshal.SizeOf(fmtChunk) + Marshal.SizeOf(riffChunk) + lenbytes); wavHeader.rifftype = new char[4]; wavHeader.rifftype[0] = 'W'; wavHeader.rifftype[1] = 'A'; wavHeader.rifftype[2] = 'V'; wavHeader.rifftype[3] = 'E'; fs = new FileStream("record.wav", FileMode.Create, FileAccess.Write); /* * Write out the WAV header. */ IntPtr wavHeaderPtr = Marshal.AllocHGlobal(Marshal.SizeOf(wavHeader)); IntPtr fmtChunkPtr = Marshal.AllocHGlobal(Marshal.SizeOf(fmtChunk)); IntPtr dataChunkPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dataChunk)); byte [] wavHeaderBytes = new byte[Marshal.SizeOf(wavHeader)]; byte [] fmtChunkBytes = new byte[Marshal.SizeOf(fmtChunk)]; byte [] dataChunkBytes = new byte[Marshal.SizeOf(dataChunk)]; Marshal.StructureToPtr(wavHeader, wavHeaderPtr, false); Marshal.Copy(wavHeaderPtr, wavHeaderBytes, 0, Marshal.SizeOf(wavHeader)); Marshal.StructureToPtr(fmtChunk, fmtChunkPtr, false); Marshal.Copy(fmtChunkPtr, fmtChunkBytes, 0, Marshal.SizeOf(fmtChunk)); Marshal.StructureToPtr(dataChunk, dataChunkPtr, false); Marshal.Copy(dataChunkPtr, dataChunkBytes, 0, Marshal.SizeOf(dataChunk)); fs.Write(wavHeaderBytes, 0, Marshal.SizeOf(wavHeader)); fs.Write(fmtChunkBytes, 0, Marshal.SizeOf(fmtChunk)); fs.Write(dataChunkBytes, 0, Marshal.SizeOf(dataChunk)); /* * Lock the sound to get access to the raw data. */ sound.@lock(0, lenbytes, ref ptr1, ref ptr2, ref len1, ref len2); /* * Write it to disk. */ byte [] rawdata = new byte[len1]; Marshal.Copy(ptr1, rawdata, 0, (int)len1); fs.Write(rawdata, 0, (int)len1); /* * Unlock the sound to allow FMOD to use it again. */ sound.unlock(ptr1, ptr2, len1, len2); fs.Close(); MessageBox.Show("Written to record.wav"); }
private void playButton_Click(object sender, System.EventArgs e) { uint version = 0; FMOD.RESULT result; /* * 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); result = system.createSound("../../../../../examples/media/wave.mp3", FMOD.MODE.OPENONLY | FMOD.MODE.ACCURATETIME, ref sound); ERRCHECK(result); /* * Decode the sound and write it to a .raw file. */ { IntPtr data = Marshal.AllocHGlobal(CHUNKSIZE); byte[] buffer = new byte[CHUNKSIZE]; uint length = 0, read = 0; uint bytesread = 0; FileStream fs = new FileStream("output.raw", FileMode.Create, FileAccess.Write); result = sound.getLength(ref length, FMOD.TIMEUNIT.PCMBYTES); ERRCHECK(result); bytesread = 0; do { result = sound.readData(data, CHUNKSIZE, ref read); Marshal.Copy(data, buffer, 0, CHUNKSIZE); fs.Write(buffer, 0, (int)read); bytesread += read; statusBar.Text = "writing " + bytesread + " bytes of " + length + " to output.raw"; }while(result == FMOD.RESULT.OK && read == CHUNKSIZE); statusBar.Text = "done"; /* * Loop terminates when either * 1. the read function returns an error. (ie FMOD_ERR_FILE_EOF etc). * 2. the amount requested was different to the amount returned. (somehow got an EOF without the file error, maybe a non stream file format like mod/s3m/xm/it/midi). * * If 'bytesread' is bigger than 'length' then it just means that FMOD miscalculated the size, * but this will not usually happen if FMOD_ACCURATETIME is used. (this will give the correct length for VBR formats) */ fs.Close(); /* * Shut down */ if (sound != null) { result = sound.release(); ERRCHECK(result); } if (system != null) { result = system.close(); ERRCHECK(result); result = system.release(); ERRCHECK(result); } } }
public static void Update(GameTime gameTime) { system.update(); if (IsSongPlaying()) { uint length = 0; uint position = 0; CurrentSong.getLength(out length, FMOD.TIMEUNIT.MS); Channel.getPosition(out position, FMOD.TIMEUNIT.MS); if (position == length) { NextSongEvent.Invoke(); } // BPM Method 1 (More research) #region Update System & FFT Algorithm if (FFTEnabled) { // Perform a Fast Fourier Transform int windowSize = spectrum.Length; //Samples. IntPtr data; uint fft_length; //hanning bpm MyDSP.setParameterInt((int)FMOD.DSP_FFT.WINDOWTYPE, (int)FMOD.DSP_FFT_WINDOW.HAMMING); MyDSP.setParameterInt((int)FMOD.DSP_FFT.WINDOWSIZE, windowSize); MyDSP.getParameterData((int)FMOD.DSP_FFT.SPECTRUMDATA, out data, out fft_length); MyDSP.getParameterFloat((int)FMOD.DSP_FFT.DOMINANT_FREQ, out higher_freq); fftParameter = (FMOD.DSP_PARAMETER_FFT)Marshal.PtrToStructure(data, typeof(FMOD.DSP_PARAMETER_FFT)); #region BPMDetection if (fftParameter.spectrum.Length != 0) { for (int i = 0; i < windowSize; i++) { if (fftParameter.spectrum.Length == 2) { spectrum[i] = (fftParameter.spectrum[0][i] + fftParameter.spectrum[1][i]) / 2f; } } } previousSpectrum = spectrum; #endregion } #endregion // BPM Method 2 (Working! but with small sync bugs) float bps = (60f / BPM); bpm_elapsed += (float)gameTime.ElapsedGameTime.TotalSeconds; if (bpm_elapsed > bps) { gotBeat = true; offBeatDelay += (float)gameTime.ElapsedGameTime.TotalSeconds; if (offBeatDelay > bps) { gotBeat = false; bpm_elapsed = 0f; offBeatDelay = 0f; } } } Channel.setVolume(masterVolume * musicVolume); }
} // GetSpectrumData private void analyzeSoundTrack() { uint endPosition = 0u; uint currentPosition = 0u; // reset all of the counters and such in the frequency band foreach (var current in m_mapOfFrequencyBands) { // clear and allocate new data arrays current.Value.reset((uint)(m_sequence.TotalEventPeriods + 1)); } // end reset the data arrays // m_FMOD_sound.release(); // m_FMOD_system.close(); // m_FMOD_system.release(); FMOD_ERRCHECK(FMOD.Factory.System_Create(ref m_FMOD_system)); m_FMOD_system.setOutput(FMOD.OUTPUTTYPE.NOSOUND_NRT); FMOD_ERRCHECK(m_FMOD_system.init(32, FMOD.INITFLAG.STREAM_FROM_UPDATE, IntPtr.Zero)); m_FMOD_system.createStream(Path.Combine(Paths.AudioPath, m_sequence.Audio.FileName), (FMOD.MODE) 72u, ref m_FMOD_sound); // How much music is there (in ms) m_FMOD_sound.getLength(ref endPosition, FMOD.TIMEUNIT.MS); // set up a progress bar TranscribeDialog transcribeDialog = new TranscribeDialog((int)endPosition); transcribeDialog.Show(); // set up the playback FMOD_ERRCHECK(m_FMOD_system.playSound(FMOD.CHANNELINDEX.FREE, m_FMOD_sound, false, ref m_FMOD_channel)); // while there is more sound to process while (currentPosition < endPosition) { // GET the playback index m_FMOD_channel.getPosition(ref currentPosition, FMOD.TIMEUNIT.MS); uint currentPeriod = ((uint)currentPosition / (uint)m_sequence.EventPeriod); // tell the user where we are in the process transcribeDialog.Progress = (int)currentPosition; transcribeDialog.Refresh(); // calculate the frequency bands for the current position GetSpectrumData(currentPeriod); // which period are we in? if (currentPeriod >= m_sequence.TotalEventPeriods) { // time to stop break; } // last period check m_FMOD_system.update(); } // end while // turn it all off m_FMOD_channel.stop(); transcribeDialog.Hide(); transcribeDialog.Dispose(); m_FMOD_sound.release(); m_FMOD_sound = null; m_FMOD_system.close(); m_FMOD_system.release(); m_FMOD_system = null; } // analyzeSoundTrack