void backWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { System.ComponentModel.BackgroundWorker b = sender as System.ComponentModel.BackgroundWorker; int samples = 32; short[] buffer = new short[samples]; bw = new BinaryWriter(File.Open(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Code.huf", FileMode.Create)); stream = Bass.BASS_StreamCreateFile(path, 0L, 0L, BASSFlag.BASS_STREAM_DECODE); ww = new WaveWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/HufSound.wav", stream, true); int mult = 0; long len = Bass.BASS_ChannelGetLength(stream, BASSMode.BASS_POS_BYTES); while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING) { int length = Bass.BASS_ChannelGetData(stream, buffer, samples * 2); mult++; b.ReportProgress((int)(((samples * mult) * 100) / len * 2)); List <short> listBuffer = new List <short>(); HuffmanTree tree = new HuffmanTree(); if (length > 0) { listBuffer.AddRange(buffer); short[] auxbuf = new short[buffer.Length]; auxbuf = buffer; canvasWavComp.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.SystemIdle, new Action(delegate { //Whole Wave //double xScale = canvasWavComp.Width / samples; //Formula by Manuel García. Dude you're amazing. //NOTE: multiply by 2 'cos I supoused some relation with Nyquist Theorem double xScale = (canvasWavComp.Width * samples) / len * 2; double yScale = (canvasWavComp.Height / (double)(amplitude * 2)) * ((double)amplitude / MAX_AMP); Polyline graphLine = new Polyline(); //This Line is used to move on the x axis Canvas.SetLeft(graphLine, xAxis); graphLine.Stroke = new SolidColorBrush(Color.FromRgb(244, 67, 54)); graphLine.StrokeThickness = 2; for (int i = 0; i < buffer.Length; i++) { graphLine.Points.Add(new Point(xScale * i, (canvasWavComp.Height / 2) - (buffer[i] * yScale))); } xAxis += xScale; //canvasWavComp.Children.Clear(); canvasWavComp.Children.Add(graphLine); })); double entaux = 0; foreach (var sym in listBuffer.GroupBy(i => i)) { NodeHuf nodeHuf = new NodeHuf(); nodeHuf.Symbol = sym.Key; nodeHuf.Frequency = sym.Count(); nodeHuf.Right = nodeHuf.Left = null; tree.Add(nodeHuf); double prob = (double)nodeHuf.Frequency / samples; //entropy -= prob * (Math.Log(prob) / Math.Log(2)); entaux += prob * Math.Log(1 / (prob), 2); entauxlbl = entaux; } entropy += entaux; entcount++; tree.Build(); //Encode System.Collections.BitArray encoded = tree.Encode(auxbuf); byte[] arrayBytes = new byte[encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1)]; encoded.CopyTo(arrayBytes, 0); File.WriteAllBytes("Compress.bin", arrayBytes); //Decode byte[] data; Stream fs = File.OpenRead("Compress.bin"); data = new byte[fs.Length]; fs.Read(data, 0, data.Length); System.Collections.BitArray bitDec = new System.Collections.BitArray(data); short[] decoded = tree.Decode(bitDec); if (decoded.Length > 0) { ww.Write(decoded, length); } bw.Write(data); fs.Close(); } } //Delete temporaly file File.Delete("Compress.bin"); //Close de Stream WAV ww ww.Close(); //If you not add this line, the backgroundworker will be restat but when file is create again //there will be an incongruence because the bw never was closed. bw.Close(); entropy /= entcount;// (len / samples); entcount = 0; }
private bool DoSplitMogg(string folder, string StemsToSplit, MoggSplitFormat format, string quality) { var ext = "ogg"; if (format == MoggSplitFormat.WAV) { ext = "wav"; } if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var drums = folder + "drums." + ext; var drums1 = folder + "drums_1." + ext; var drums2 = folder + "drums_2." + ext; var drums3 = folder + "drums_3." + ext; var bass = folder + "bass." + ext; var rhythm = folder + "rhythm." + ext; var guitar = folder + "guitar." + ext; var keys = folder + "keys." + ext; var vocals = folder + "vocals." + ext; var backing = folder + "backing." + ext; var song = folder + "song." + ext; var crowd = folder + "crowd." + ext; var tracks = new List <string> { drums, drums1, drums2, drums3, bass, guitar, keys, vocals, backing, crowd }; foreach (var track in tracks) { Tools.DeleteFile(track); } try { if (!InitBass()) { return(false); } SourceStream = Bass.BASS_StreamCreateFile(Tools.GetOggStreamIntPtr(), 0, Tools.PlayingSongOggData.Length, BASSFlag.BASS_STREAM_DECODE); var info = Bass.BASS_ChannelGetInfo(SourceStream); var ArrangedChannels = ArrangeStreamChannels(info.chans, true); var isSlave = false; if (Parser.Songs[0].ChannelsDrums > 0 && (StemsToSplit.Contains("allstems") || StemsToSplit.Contains("drums"))) { switch (Parser.Songs[0].ChannelsDrums) { case 2: PrepareChannelsToSplit(0, ArrangedChannels, 2, GetStemVolume(0), drums, format, quality, false); break; case 3: PrepareChannelsToSplit(0, ArrangedChannels, 1, GetStemVolume(0), drums1, format, quality, false); PrepareChannelsToSplit(1, ArrangedChannels, 2, GetStemVolume(1), drums2, format, quality); break; case 4: PrepareChannelsToSplit(0, ArrangedChannels, 1, GetStemVolume(0), drums1, format, quality, false); PrepareChannelsToSplit(1, ArrangedChannels, 1, GetStemVolume(1), drums2, format, quality); PrepareChannelsToSplit(2, ArrangedChannels, 2, GetStemVolume(2), drums3, format, quality); break; case 5: PrepareChannelsToSplit(0, ArrangedChannels, 1, GetStemVolume(0), drums1, format, quality, false); PrepareChannelsToSplit(1, ArrangedChannels, 2, GetStemVolume(1), drums2, format, quality); PrepareChannelsToSplit(3, ArrangedChannels, 2, GetStemVolume(3), drums3, format, quality); break; case 6: PrepareChannelsToSplit(0, ArrangedChannels, 2, GetStemVolume(0), drums1, format, quality, false); PrepareChannelsToSplit(2, ArrangedChannels, 2, GetStemVolume(2), drums2, format, quality); PrepareChannelsToSplit(4, ArrangedChannels, 2, GetStemVolume(4), drums3, format, quality); break; } isSlave = true; } var channel = Parser.Songs[0].ChannelsDrums; if (Parser.Songs[0].ChannelsBass > 0 && (StemsToSplit.Contains("allstems") || StemsToSplit.Contains("bass") || StemsToSplit.Contains("rhythm"))) { PrepareChannelsToSplit(channel, ArrangedChannels, Parser.Songs[0].ChannelsBass, GetStemVolume(channel), StemsToSplit.Contains("rhythm") ? rhythm : bass, format, quality, isSlave); isSlave = true; } channel += Parser.Songs[0].ChannelsBass; if (Parser.Songs[0].ChannelsGuitar > 0 && (StemsToSplit.Contains("allstems") || StemsToSplit.Contains("guitar"))) { PrepareChannelsToSplit(channel, ArrangedChannels, Parser.Songs[0].ChannelsGuitar, GetStemVolume(channel), guitar, format, quality, isSlave); isSlave = true; } channel += Parser.Songs[0].ChannelsGuitar; if (Parser.Songs[0].ChannelsVocals > 0 && (StemsToSplit.Contains("allstems") || StemsToSplit.Contains("vocals"))) { PrepareChannelsToSplit(channel, ArrangedChannels, Parser.Songs[0].ChannelsVocals, GetStemVolume(channel), vocals, format, quality, isSlave); isSlave = true; } channel += Parser.Songs[0].ChannelsVocals; if (Parser.Songs[0].ChannelsKeys > 0 && (StemsToSplit.Contains("allstems") || StemsToSplit.Contains("keys"))) { PrepareChannelsToSplit(channel, ArrangedChannels, Parser.Songs[0].ChannelsKeys, GetStemVolume(channel), keys, format, quality, isSlave); isSlave = true; } channel += Parser.Songs[0].ChannelsKeys; if (Parser.Songs[0].ChannelsBacking() > 0 && (StemsToSplit.Contains("allstems") || StemsToSplit.Contains("backing") || StemsToSplit.Contains("song"))) { PrepareChannelsToSplit(channel, ArrangedChannels, Parser.Songs[0].ChannelsBacking(), GetStemVolume(channel), StemsToSplit.Contains("song") ? song : backing, format, quality, isSlave); isSlave = true; } channel += Parser.Songs[0].ChannelsBacking(); if (Parser.Songs[0].ChannelsCrowd > 0 && (StemsToSplit.Contains("allstems") || StemsToSplit.Contains("crowd"))) { PrepareChannelsToSplit(channel, ArrangedChannels, Parser.Songs[0].ChannelsCrowd, GetStemVolume(channel), crowd, format, quality, isSlave); } while (true) { var buffer = new byte[20000]; var c = Bass.BASS_ChannelGetData(Splits[0], buffer, buffer.Length); if (c < 0) { break; } for (var i = 1; i < Splits.Count; i++) { while (Bass.BASS_ChannelGetData(Splits[i], buffer, buffer.Length) > 0) { } } } foreach (var split in Splits) { Bass.BASS_StreamFree(split); } UnloadLibraries(); Tools.ReleaseStreamHandle(); } catch (Exception ex) { ErrorLog.Add("Error splitting mogg file:"); ErrorLog.Add(ex.Message); foreach (var split in Splits) { Bass.BASS_StreamFree(split); } UnloadLibraries(); Tools.ReleaseStreamHandle(); return(false); } return(true); }
/// <summary> /// Read mono from file /// </summary> /// <param name = "filename">Name of the file</param> /// <param name = "samplerate">Sample rate</param> /// <param name = "milliseconds">milliseconds to read</param> /// <param name = "startmillisecond">Start millisecond</param> /// <returns>Array of samples</returns> public float[] ReadMonoFromFile(string filename, int samplerate, int milliseconds, int startmillisecond) { //поробовать переделать эту фуункцию под float[] int totalmilliseconds = milliseconds <= 0 ? Int32.MaxValue : milliseconds + startmillisecond; float[] data = null; //create streams for re-sampling int stream = Bass.BASS_StreamCreateFile(filename, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); //Decode the stream if (stream == 0) { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } int mixerStream = BassMix.BASS_Mixer_StreamCreate(samplerate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT); if (mixerStream == 0) { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER)) { const int bufferSize = 5512 * 10 * 4; /*read ten seconds at each iteration*/ float[] buffer = new float[bufferSize]; List <float[]> chunks = new List <float[]>(); int size = 0; while ((float)(size) / samplerate * 1000 < totalmilliseconds) { //get re-sampled/mono data int bytesRead = Bass.BASS_ChannelGetData(mixerStream, buffer, bufferSize); if (bytesRead == 0) { break; } float[] chunk = new float[bytesRead / 4]; //each float contains 4 bytes Array.Copy(buffer, chunk, bytesRead / 4); chunks.Add(chunk); size += bytesRead / 4; //size of the data } if ((float)(size) / samplerate * 1000 < (milliseconds + startmillisecond)) { return(null); /*not enough samples to return the requested data*/ } int start = (int)((float)startmillisecond * samplerate / 1000); int end = (milliseconds <= 0) ? size : (int)((float)(startmillisecond + milliseconds) * samplerate / 1000); data = new float[size]; int index = 0; /*Concatenate*/ foreach (float[] chunk in chunks) { Array.Copy(chunk, 0, data, index, chunk.Length); index += chunk.Length; } /*Select specific part of the song*/ if (start != 0 || end != size) { float[] temp = new float[end - start]; Array.Copy(data, start, temp, 0, end - start); data = temp; } } else { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } return(data); }
public static void ExportWAV(string srcPath, string destPath, ExportOptions exportOptions) { Debug.Log("Exporting " + srcPath + " to " + destPath); int stream = Bass.BASS_StreamCreateFile(srcPath, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT); if (stream == 0 || Bass.BASS_ErrorGetCode() != BASSError.BASS_OK) { throw new Exception(Bass.BASS_ErrorGetCode().ToString()); } WaveWriter ww = new WaveWriter(destPath, stream, true); float[] data = new float[32768]; while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING) { // get the sample data as float values as well int length = Bass.BASS_ChannelGetData(stream, data, 32768); // and write the data to the wave file if (length > 0) { ww.Write(data, length); } } ww.Close(); Bass.BASS_StreamFree(stream); /* * const int WAV_HEADER_LENGTH = 44; * * * * FileStream ifs = null; * BinaryReader br = null; * * FileStream ofs = null; * BinaryWriter bw = null; * * try * { * ifs = new FileStream(srcPath, FileMode.Open, FileAccess.Read); * br = new BinaryReader(ifs); * * ofs = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write); * bw = new BinaryWriter(ofs); * * ifs.Seek(0, SeekOrigin.Begin); * * byte[] header = br.ReadBytes(WAV_HEADER_LENGTH); * * ifs.Seek(4, SeekOrigin.Begin); * int chunkLength = br.ReadInt32(); // bytes 4 to 7 * * ifs.Seek(16, SeekOrigin.Current); * int frequency = br.ReadInt32(); * int byterate = br.ReadInt32(); * * ifs.Seek(WAV_HEADER_LENGTH, SeekOrigin.Begin); * byte[] chunk = br.ReadBytes(chunkLength); * * * } * catch * { * Debug.LogError("Error with writing wav file"); * } * finally * { * try { br.Close(); } * catch { } * * try { ifs.Close(); } * catch { } * * try { bw.Close(); } * catch { } * * try { ofs.Close(); } * catch { } * } */ }
public int ChannelGetData(int stream, float[] buffer, int lengthInBytes) { return(Bass.BASS_ChannelGetData(stream, buffer, lengthInBytes)); }
public void GetSpectrum(int _stream, out float[] _buffer) { _buffer = new float[256]; Bass.BASS_ChannelGetData(_stream, _buffer, (int)(BASSData.BASS_DATA_FFT512 | BASSData.BASS_DATA_FFT_COMPLEX)); }
public bool GetWaveData32(int length, out float[] waveData32) { waveData32 = new float[length]; return(_vizStream != null && Bass.BASS_ChannelGetData(_vizStream.Handle, waveData32, length) == (int)BASSError.BASS_OK); }
public bool GetFFTData(float[] fftDataBuffer) { return(Bass.BASS_ChannelGetData(ActiveStreamHandle, fftDataBuffer, maxFFT) > 0); }
private void FrameConverter_DoWork(object sender, DoWorkEventArgs e) { try { // Initialize BASS and variables Bass.BASS_Init(0, 44100, BASSInit.BASS_DEVICE_NOSPEAKER, IntPtr.Zero); Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_MIDI_VOICES, 0); Data.StreamHandle = BassMidi.BASS_MIDI_StreamCreateFile(Data.MIDIToLoad, 0L, 0L, BASSFlag.BASS_MIDI_NOCROP | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_MIDI_DECAYEND, 0); Data.PlayedNotesAvg = new List <Double>(); // Check if the MIDI file is valid BASSError Error = Bass.BASS_ErrorGetCode(); if (Error == BASSError.BASS_ERROR_ILLPARAM || Error == BASSError.BASS_ERROR_FILEOPEN || Error == BASSError.BASS_ERROR_FILEFORM) { MessageBox.Show("Invalid MIDI file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Settings.Interrupt = true; return; } Data.OsuemSize = Properties.Settings.Default.CounterFont.Size; Int64 StreamLength = Bass.BASS_ChannelGetLength(Data.StreamHandle); Int32 ChunkLength = Convert.ToInt32(Bass.BASS_ChannelSeconds2Bytes(Data.StreamHandle, FFMPEGProcess.Hertz)); Byte[] Buffer; // Initialize played notes sync Data.NoteSync = new SYNCPROC(NoteSyncProc); Bass.BASS_ChannelSetSync(Data.StreamHandle, BASSSync.BASS_SYNC_MIDI_EVENT, (long)BASSMIDIEvent.MIDI_EVENT_NOTE, Data.NoteSync, IntPtr.Zero); // Initialize time signature sync BassMidi.BASS_MIDI_StreamGetMark(Data.StreamHandle, BASSMIDIMarker.BASS_MIDI_MARK_TIMESIG, 0, Data.Mark); Data.TimeSigSync = new SYNCPROC(TimeSigSyncProc); Bass.BASS_ChannelSetSync(Data.StreamHandle, BASSSync.BASS_SYNC_MIDI_TIMESIG, (long)BASSMIDIMarker.BASS_MIDI_MARK_TIMESIG, Data.TimeSigSync, IntPtr.Zero); // Initialize note count Data.TotalNotes = Convert.ToUInt32(BassMidi.BASS_MIDI_StreamGetEvents(Data.StreamHandle, -1, (BASSMIDIEvent)0x20000, null)); Data.HowManyZeroesNotes = "00000"; // Initialize conversion if (!StartConversion(Data.MIDIToLoad)) { return; } FPSUpdate(); if (Properties.Settings.Default.StillFramesBeginning) { for (int a = 0; a <= (Properties.Settings.Default.FPSExport * 5); a++) { // 5 seconds of nothing if (Settings.Interrupt == true) { break; } CheckPosition(); Data.NotesPerSecond = "0"; PushFrame(false); FFMPEGProcess.Frames++; FPSUpdate(); } } while (Bass.BASS_ChannelIsActive(Data.StreamHandle) == BASSActive.BASS_ACTIVE_PLAYING) { if (Data.OsuemSize > Properties.Settings.Default.CounterFont.Size) { Data.OsuemSize -= (Properties.Settings.Default.CounterFont.Size / 24); if (Data.OsuemSize < Properties.Settings.Default.CounterFont.Size) { Data.OsuemSize = Properties.Settings.Default.CounterFont.Size; } } else { Data.OsuemSize = Properties.Settings.Default.CounterFont.Size; } if (Settings.Interrupt == true) { break; } Buffer = new Byte[ChunkLength]; Bass.BASS_ChannelGetData(Data.StreamHandle, Buffer, ChunkLength); CheckPosition(); if (FFMPEGProcess.Frames % (ulong)Properties.Settings.Default.FPSExport == 0) { Data.NotesPerSecond = Data.PlayedNotesFrame.ToString(); Data.PlayedNotesAvg.Add(Data.PlayedNotesFrame); Data.AverageNotesPerSecond = Data.PlayedNotesAvg.Average().ToString("0.0"); Data.PlayedNotesFrame = 0; } PushFrame(false); FFMPEGProcess.Frames++; FPSUpdate(); } Buffer = new Byte[ChunkLength]; Bass.BASS_ChannelGetData(Data.StreamHandle, Buffer, ChunkLength); if (Properties.Settings.Default.StillFramesEnd) { for (int a = 0; a <= (Properties.Settings.Default.FPSExport * 5); a++) { if (Data.OsuemSize > Properties.Settings.Default.CounterFont.Size) { Data.OsuemSize -= (Properties.Settings.Default.CounterFont.Size / 24); if (Data.OsuemSize < Properties.Settings.Default.CounterFont.Size) { Data.OsuemSize = Properties.Settings.Default.CounterFont.Size; } } else { Data.OsuemSize = Properties.Settings.Default.CounterFont.Size; } // 5 seconds of nothing if (Settings.Interrupt == true) { break; } CheckPosition(); Data.NotesPerSecond = "0"; PushFrame(false); FFMPEGProcess.Frames++; FPSUpdate(); } } for (int i = 0; i < Data.PlayedNotesChan.Length; i++) { Data.PlayedNotesChan[i] = 0; } Data.Mark = new BASS_MIDI_MARK(); FFMPEGProcess.Frames = 0; FFMPEGProcess.FFMPEG.StandardInput.Close(); Bass.BASS_StreamFree(Data.StreamHandle); Bass.BASS_Free(); Settings.Interrupt = false; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public bool ProcessAudio(int channel, bool bpmBeatsOnly) { if (channel == 0) { return(false); } this.beat = false; this.bpmBeat = false; this.subbandBeatHits = 0.0; if (this._startCounter <= this._historyCount) { this._startCounter++; } try { if (Bass.BASS_ChannelGetData(channel, this._fft, -2147483647) > 0) { for (int i = 1; i < 128; i++) { this.Es = this._fft[i]; if (this._startCounter > this._historyCount) { this.avgE = this.AverageLocalEnergy(i); this.varianceE = this.VarianceLocalEnergy(i, this.avgE); this.envIn = (double)this.Es / (double)this.avgE; if (this.avgE > 0f) { if (this.envIn > this._peakEnv[i]) { this._peakEnv[i] = this.envIn; } else { this._peakEnv[i] *= this._beatRelease; this._peakEnv[i] += (1.0 - this._beatRelease) * this.envIn; } if (!this._beatTrigger[i]) { if (i <= this._LFfftBin1) { if (this._peakEnv[i] > 1.7 * (double)((this.avgE + this.varianceE) / this.avgE)) { this._beatTrigger[i] = true; } } else if (i >= this._MFfftBin0 && i <= this._MFfftBin1) { if (this._peakEnv[i] > 2.4 * (double)((this.avgE + this.varianceE) / this.avgE)) { this._beatTrigger[i] = true; } } else if (this._peakEnv[i] > 2.8 * (double)((this.avgE + this.varianceE) / this.avgE)) { this._beatTrigger[i] = true; } } else if (i <= this._LFfftBin1) { if (this._peakEnv[i] < 1.4 * (double)((this.avgE + this.varianceE) / this.avgE)) { this._beatTrigger[i] = false; } } else if (i >= this._MFfftBin0 && i <= this._MFfftBin1) { if (this._peakEnv[i] < 1.1 * (double)((this.avgE + this.varianceE) / this.avgE)) { this._beatTrigger[i] = false; } } else if (this._peakEnv[i] < 1.4 * (double)((this.avgE + this.varianceE) / this.avgE)) { this._beatTrigger[i] = false; } if (this._beatTrigger[i] && !this._prevBeatPulse[i]) { if (i <= this._LFfftBin1) { this.subbandBeatHits += 100.0 * (double)(this.avgE / this.varianceE); } else if (i >= this._MFfftBin0 && i <= this._MFfftBin1) { this.subbandBeatHits += 10.0 * (double)(this.avgE / this.varianceE); } else { this.subbandBeatHits += 2.0 * (double)(this.avgE / this.varianceE); } } this._prevBeatPulse[i] = this._beatTrigger[i]; } } else { this._nextBeatStart = DateTime.Now; this._nextBeatEnd = this._nextBeatStart.AddMilliseconds(330.0); } this.ShiftHistoryEnergy(i); this._historyEnergy[i][0] = this.Es; } if (this.subbandBeatHits > this._peakSubbandBeatHits) { this._peakSubbandBeatHits = this.subbandBeatHits; } else { this._peakSubbandBeatHits = (this._peakSubbandBeatHits + this.subbandBeatHits) / 2.0; } if (!this._beatTriggerC) { if (this._peakSubbandBeatHits > 200.0) { this._beatTriggerC = true; this.beatTime = DateTime.Now; } } else if (this._peakSubbandBeatHits < 100.0) { this._beatTriggerC = false; } if (this._beatTriggerC && !this._prevBeatPulseC) { this.beat = true; } this._prevBeatPulseC = this._beatTriggerC; if (this.beat) { if (this._beatTriggerD) { this.deltaMS = Math.Round((this.beatTime - this._lastBeatTime).TotalMilliseconds); if (this.deltaMS < 333.0 && this._peakSubbandBeatHits < this._prevPeakSubbandBeatHits) { this.beat = false; this.beatTime = this._lastBeatTime; } else { this._prevPeakSubbandBeatHits = this._peakSubbandBeatHits; if (this.beatTime >= this._nextBeatStart && this.beatTime <= this._nextBeatEnd) { this.BPM = this.MillisecondsToBPM(this.deltaMS); this.bpmBeat = true; this._nextBeatStart = this.beatTime.AddMilliseconds((1.0 - this._beatRelease) * this.deltaMS); this._nextBeatEnd = this.beatTime.AddMilliseconds((1.0 + this._beatRelease) * this.deltaMS); } else if (this.beatTime < this._nextBeatStart) { this._beatTriggerD = false; } } if (this.beatTime > this._nextBeatEnd) { this._nextBeatStart = this.beatTime.AddMilliseconds((1.0 - this._beatRelease) * this.deltaMS); this._nextBeatEnd = this.beatTime.AddMilliseconds((1.0 + this._beatRelease) * this.deltaMS); } } this._lastBeatTime = this.beatTime; this._beatTriggerD = true; } } } catch { } if (bpmBeatsOnly) { return(this.bpmBeat); } return(this.beat); }
private static string[] SplitAudio(string fileName, double[] segments, string prefix, string outputDirectory) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (segments == null) { throw new ArgumentNullException("segments"); } if (prefix == null) { throw new ArgumentNullException("prefix"); } if (outputDirectory == null) { throw new ArgumentNullException("outputDirectory"); } int i = Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_PRESCAN | BASSFlag.BASS_STREAM_DECODE); if (i == 0) { throw new InvalidOperationException("Couldn't create stream"); } double sum = segments.Sum(); long length = Bass.BASS_ChannelGetLength(i); double seconds = Bass.BASS_ChannelBytes2Seconds(i, length); if (sum > seconds) { throw new ArgumentOutOfRangeException("segments", "Required segments exceed file duration"); } BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(i); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } int index = 0; var list = new List <string>(); foreach (double segment in segments) { double d = segment; long seconds2Bytes = Bass.BASS_ChannelSeconds2Bytes(i, d); var buffer = new byte[seconds2Bytes]; int getData = Bass.BASS_ChannelGetData(i, buffer, buffer.Length); string name = string.Format("{0}_{1}.wav", prefix, index); string combine = Path.Combine(outputDirectory, name); int bitsPerSample = info.Is8bit ? 8 : info.Is32bit ? 32 : 16; var waveWriter = new WaveWriter(combine, info.chans, info.freq, bitsPerSample, true); waveWriter.WriteNoConvert(buffer, buffer.Length); waveWriter.Close(); list.Add(combine); index++; } bool free = Bass.BASS_StreamFree(i); return(list.ToArray()); }
public void Evaluate(int SpreadMax) { if (this.FPinInHandle.PinIsChanged || this.FChannel == null) { //Just Update the Handle double dhandle; this.FPinInHandle.GetValue(0, out dhandle); int ihandle = Convert.ToInt32(Math.Round(dhandle)); if (this.FManager.Exists(ihandle)) { this.FChannel = this.FManager.GetChannel(ihandle); if (this.FChannel.BassHandle.HasValue) { if (this.FChannel.IsDecoding) { int mixhandle = BassMix.BASS_Mixer_ChannelGetMixer(this.FChannel.BassHandle.Value); if (mixhandle == 0) { // create a buffer of the source stream //We can't get it from the main stream otherwise it would interfere with the asio buffering bufferStream = new DSP_BufferStream(); bufferStream.ChannelHandle = this.FChannel.BassHandle.Value; // the stream to copy bufferStream.DSPPriority = -4000; bufferStream.Start(); this.FMyBassHandle = bufferStream.BufferStream; this.FMixer = false; } else { //We have a mixer, much better :) this.FMyBassHandle = this.FChannel.BassHandle.Value; this.FMixer = true; } } else { //If it's not decoding, no problem :) this.FMyBassHandle = this.FChannel.BassHandle.Value; this.FMixer = false; } } else { this.FMyBassHandle = 0; this.FChannel = null; } } else { this.FMyBassHandle = 0; this.FChannel = null; } } int len = this.DataLength; this.FPinOutSize.SetValue(0, len); if (len != -1) { BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(this.FChannel.BassHandle.Value); //We get float, so length is divided by 4 float[] samples = new float[len]; int val; if (this.FMixer) { val = BassMix.BASS_Mixer_ChannelGetData(this.FMyBassHandle, samples, this.DataType); } else { val = Bass.BASS_ChannelGetData(this.FMyBassHandle, samples, this.DataType); } this.SetData(samples); this.FPinOutMsg.SetString(0, "OK"); } else { this.FPinOutMsg.SetString(0, this.ErrorMsg); } }
public int ChannelGetData(int pChannel, float[] pFft, int pFftLength) { return(Bass.BASS_ChannelGetData(pChannel, pFft, pFftLength)); }
//複数のサウンドを合体(Posにマイナスが含まれている場合バグります //引数:合体させるファイル, サウンドの開始位置, 音量, 再生速度, 保存先, MP3として保存するか(falseの場合は.wav形式), 元のファイルを削除するか public static void Sound_Combine(List <string> Files, List <double> Pos, List <double> Volume, List <double> Speed, string To_File, bool IsEncodeMP3, bool IsFromFileDelete = false) { int mixer = BassMix.BASS_Mixer_StreamCreate(48000, 2, BASSFlag.BASS_STREAM_DECODE); long Mixer_Max_Length = 0; List <int> Streams = new List <int>(); List <int> Stream_Handles = new List <int>(); //ファイルをミックスする for (int Number = 0; Number < Files.Count; Number++) { Streams.Add(Bass.BASS_StreamCreateFile(Files[Number], 0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE)); Stream_Handles.Add(BassFx.BASS_FX_TempoCreate(Streams[Streams.Count - 1], BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_FX_FREESOURCE)); float Freq = 48000; Bass.BASS_ChannelGetAttribute(Stream_Handles[Stream_Handles.Count - 1], BASSAttribute.BASS_ATTRIB_TEMPO_FREQ, ref Freq); Bass.BASS_ChannelSetAttribute(Stream_Handles[Stream_Handles.Count - 1], BASSAttribute.BASS_ATTRIB_TEMPO_FREQ, Freq * (float)Speed[Number]); Bass.BASS_ChannelSetAttribute(Stream_Handles[Stream_Handles.Count - 1], BASSAttribute.BASS_ATTRIB_VOL, (float)(Volume[Number] / 100)); long start = Bass.BASS_ChannelSeconds2Bytes(mixer, Pos[Number]); BassMix.BASS_Mixer_StreamAddChannelEx(mixer, Stream_Handles[Stream_Handles.Count - 1], BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE, start, 0); long Now_Stream_Length = Bass.BASS_ChannelGetLength(Streams[Streams.Count - 1], BASSMode.BASS_POS_BYTES); if (Mixer_Max_Length < Now_Stream_Length + start) { Mixer_Max_Length = Now_Stream_Length + start; } } //.wavでエンコード(こっちの方が速い + 安定性が高い) EncoderWAV l = new EncoderWAV(mixer); l.InputFile = null; l.OutputFile = To_File + ".tmp"; l.WAV_BitsPerSample = 24; l.Start(null, IntPtr.Zero, false); byte[] encBuffer = new byte[65536]; while (Bass.BASS_ChannelIsActive(mixer) == BASSActive.BASS_ACTIVE_PLAYING) { int len = Bass.BASS_ChannelGetData(mixer, encBuffer, encBuffer.Length); if (len <= 0) { break; } else if (Mixer_Max_Length <= Bass.BASS_ChannelGetPosition(mixer, BASSMode.BASS_POS_BYTES)) { break; } } l.Stop(); //メモリ解放 Bass.BASS_StreamFree(mixer); foreach (int Stream in Stream_Handles) { Bass.BASS_StreamFree(Stream); } foreach (int Stream in Streams) { Bass.BASS_StreamFree(Stream); } //MP3形式にエンコード if (IsEncodeMP3) { Un4seen.Bass.Misc.EncoderLAME mc = new Un4seen.Bass.Misc.EncoderLAME(0); mc.EncoderDirectory = Voice_Set.Special_Path + "/Encode_Mp3"; mc.InputFile = To_File + ".tmp"; mc.OutputFile = To_File; mc.LAME_Bitrate = (int)Un4seen.Bass.Misc.EncoderLAME.BITRATE.kbps_144; mc.LAME_Mode = Un4seen.Bass.Misc.EncoderLAME.LAMEMode.Default; mc.LAME_Quality = Un4seen.Bass.Misc.EncoderLAME.LAMEQuality.Q2; Un4seen.Bass.Misc.BaseEncoder.EncodeFile(mc, null, true, false, true); mc.Dispose(); File.Delete(To_File + ".tmp"); } else { Sub_Code.File_Move(To_File + ".tmp", To_File, true); } if (File.Exists(To_File) && IsFromFileDelete) { foreach (string File_Now in Files) { Sub_Code.File_Delete_V2(File_Now); } } }
//if (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING) 可以获取状态 public float[] GetFFTData(string name) { float[] fft = new float[512]; Bass.BASS_ChannelGetData(soundlist[name].stream, fft, (int)BASSData.BASS_DATA_FFT1024); return(fft); }
private void timer1_Tick(object sender, EventArgs e) { double n_data, M697, M770, M852, M941, M1209, M1336, M1477, M1633; double max; string result, s, DTMF_symbol; //получить массив n_data = Bass.BASS_ChannelGetData(stream, data, length * 2); if (n_data < length * 2) { return; //если слишком мало получено, не рассчитать } //молучаем магнитуды нужных частот M697 = GetMagnitude(697); M770 = GetMagnitude(770); M852 = GetMagnitude(852); M941 = GetMagnitude(941); M1209 = GetMagnitude(1209); M1336 = GetMagnitude(1336); M1477 = GetMagnitude(1477); M1633 = GetMagnitude(1633); max = 20; //чувствительность result = ""; //достаточна ли магнитуда s = (M697 > max) ? "1" : "0"; result = result + s; //добавляем к результату s = (M770 > max) ? "1" : "0"; result = result + s; s = (M852 > max) ? "1" : "0"; result = result + s; s = (M941 > max) ? "1" : "0"; result = result + s; s = (M1209 > max) ? "1" : "0"; result = result + s; s = (M1336 > max) ? "1" : "0"; result = result + s; s = (M1477 > max) ? "1" : "0"; result = result + s; s = (M1633 > max) ? "1" : "0"; result = result + s; DTMF_symbol = ""; //в итоге получается нечто похожее на битовое поле switch (result) { case "10001000": //1 - есть частоста, 0 - нет частоты в спектре (в зависимости от того какие частоты есть определяется символ) DTMF_symbol = "1"; break; case "10000100": DTMF_symbol = "2"; break; case "10000010": DTMF_symbol = "3"; break; case "01001000": DTMF_symbol = "4"; break; case "01000100": DTMF_symbol = "5"; break; case "01000010": DTMF_symbol = "6"; break; case "00101000": DTMF_symbol = "7"; break; case "00100100": DTMF_symbol = "8"; break; case "00100010": DTMF_symbol = "9"; break; case "00011000": DTMF_symbol = "*"; break; case "00010100": DTMF_symbol = "0"; break; case "00010010": DTMF_symbol = "#"; break; case "10000001": DTMF_symbol = "A"; break; case "01000001": DTMF_symbol = "B"; break; case "00100001": DTMF_symbol = "C"; break; case "00010001": DTMF_symbol = "D"; break; } if (DTMF_symbol != "") //символ определился { counter = 0; //отсчет завершения слова if (last_simbol != DTMF_symbol) //символ сменился { DTMF_word = DTMF_word + DTMF_symbol; //символ добавляется к слову last_simbol = DTMF_symbol; } } if (DTMF_word != "") { counter++; //у нас есть слово, ждем паузы, когда больше не будут декодироваться символы } if (counter > 5) //есть пауза { textBox1.AppendText(DTMF_word + Environment.NewLine); DTMF_word = ""; last_simbol = ""; counter = 0; } }
public bool GetFFTData(string name, float[] fft) { Bass.BASS_ChannelGetData(soundlist[name].stream, fft, (int)BASSData.BASS_DATA_FFT1024); return(true); }
public void Resample_16To16() { //-- 1. Create a raw sine sample which shall be 44100 Hz and 16 Bit int sampleLength = 500; short[] buffer = new short[sampleLength]; for (int i = 0; i < sampleLength; i++) { buffer [i] = (short)(30000.0f * Math.Sin(((float)i / (float)sampleLength) * (Math.PI * 2.0f))); } using (BinaryWriter writerRaw = new BinaryWriter(File.Open("test1_in_sine_44100_16.raw", FileMode.Create))) { for (uint i = 0; i < sampleLength; i++) { writerRaw.Write(buffer [i]); } } GCHandle _hGCFile; // now create a pinned handle, so that the Garbage Collector will not move this object _hGCFile = GCHandle.Alloc(buffer, GCHandleType.Pinned); int handle = Bass.BASS_StreamCreate(44100, 1, BASSFlag.BASS_STREAM_DECODE, BASSStreamProc.STREAMPROC_PUSH); int ret = Bass.BASS_StreamPutData(handle, _hGCFile.AddrOfPinnedObject(), buffer.Length * sizeof(short) | (int)BASSStreamProc.BASS_STREAMPROC_END); Assert.AreEqual(buffer.Length * sizeof(short), ret); //-- 2. Mix it int mixer = BassMix.BASS_Mixer_StreamCreate(11025, 1, BASSFlag.BASS_STREAM_DECODE); // add channel to mixer bool isMixerGood = BassMix.BASS_Mixer_StreamAddChannel(mixer, handle, BASSFlag.BASS_MIXER_NORAMPIN); Assert.AreEqual(true, isMixerGood); //-- 3. grab Stream and compare short[] buffer2 = new short[1000]; // total data written to the new byte[] buffer int totalDataWritten = Bass.BASS_ChannelGetData(mixer, buffer2, (int)1000); Console.WriteLine("totalDataWritten " + totalDataWritten); using (BinaryWriter writerRaw = new BinaryWriter(File.Open("test1_out_sine_11025_16.raw", FileMode.Create))) { for (uint i = 0; i < totalDataWritten / 2; i++) { writerRaw.Write(buffer2 [i]); } } byte[] buffer3 = new byte[2000]; Buffer.BlockCopy(buffer2, 0, buffer3, 0, totalDataWritten); string hashGen = MD5Utils.GenerateMd5Hash(buffer3); Bass.BASS_StreamFree(handle); Bass.BASS_StreamFree(mixer); Assert.AreEqual("2c61dc0767698eb28c7735cb073cea6c", hashGen); }
/// <summary> /// Saves audio data as a mono wave. /// </summary> /// <param name="audioData">The audio data.</param> /// <param name="outFilename">The output filename.</param> /// <param name="length">The maximum length in seconds, or 0 for no limit.</param> /// <param name="gain">The gain.</param> /// <exception cref="System.Exception">Cannot load audio data</exception> public static void SaveAsMonoWave(byte[] audioData, string outFilename, double length, float gain) { // DebugHelper.WriteLine("SaveAsMonoWave"); var audioDataHandle = GCHandle.Alloc(audioData, GCHandleType.Pinned); var audioDataPointer = audioDataHandle.AddrOfPinnedObject(); var channel = Bass.BASS_StreamCreateFile(audioDataPointer, 0, audioData.Length, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_STREAM_PRESCAN); if (channel == 0) { throw new Exception("Cannot load audio data"); } // create a mono 44100Hz mixer var mixer = BassMix.BASS_Mixer_StreamCreate(44100, 1, BASSFlag.BASS_MIXER_END | BASSFlag.BASS_STREAM_DECODE); // plug in the source BassMix.BASS_Mixer_StreamAddChannel(mixer, channel, BASSFlag.BASS_MIXER_DOWNMIX | BASSFlag.BASS_MIXER_NORAMPIN); AudioStreamHelper.SetReplayGain(mixer, gain); const BASSEncode flags = BASSEncode.BASS_ENCODE_PCM; BassEnc.BASS_Encode_Start(mixer, outFilename, flags, null, IntPtr.Zero); const int startByte = 0; if (length == 0) { length = Bass.BASS_ChannelBytes2Seconds(channel, Bass.BASS_ChannelGetLength(channel)); } var totalTransferLength = Bass.BASS_ChannelSeconds2Bytes(mixer, length); Bass.BASS_ChannelSetPosition(channel, startByte, BASSMode.BASS_POS_BYTES); while (totalTransferLength > 0) { var buffer = new byte[65536]; var transferLength = totalTransferLength; if (transferLength > buffer.Length) { transferLength = buffer.Length; } // get the decoded sample data var transferred = Bass.BASS_ChannelGetData(mixer, buffer, (int)transferLength); if (transferred <= 1) { break; // error or the end } totalTransferLength -= transferred; } BassEnc.BASS_Encode_Stop(mixer); BassMix.BASS_Mixer_ChannelRemove(channel); Bass.BASS_StreamFree(channel); Bass.BASS_StreamFree(mixer); audioDataHandle.Free(); // DebugHelper.WriteLine("END SaveAsMonoWave"); }
public static bool GetEQ(ref EQControl EQSETTINGS) { bool extensiveLogging = Settings.Instance.ExtensiveLogging; bool flag2 = (EQSETTINGS.UseStereoEq | EQSETTINGS.UseVUmeter) | EQSETTINGS.UseVUmeter2; if (g_Player.Player == null || !g_Player.IsMusic || !BassMusicPlayer.IsDefaultMusicPlayer) { return(false); } if (!EQSETTINGS.UseEqDisplay) { return(false); } if (EQSETTINGS._AudioUseASIO) { return(false); } try { if (EQSETTINGS.DelayEQ & (g_Player.CurrentPosition < EQSETTINGS._DelayEQTime)) { EQSETTINGS._EQDisplayTitle = false; EQSETTINGS._LastEQTitle = (DateTime.Now.Ticks / 1000); return(false); } if (EQSETTINGS.EQTitleDisplay) { if (g_Player.CurrentPosition < EQSETTINGS._EQTitleDisplayTime) { EQSETTINGS._EQDisplayTitle = false; } if (((DateTime.Now.Ticks / 1000) - EQSETTINGS._LastEQTitle) > (EQSETTINGS._EQTitleDisplayTime * 10000)) { EQSETTINGS._LastEQTitle = (DateTime.Now.Ticks / 1000); EQSETTINGS._EQDisplayTitle = !EQSETTINGS._EQDisplayTitle; } if (EQSETTINGS._EQDisplayTitle & (((DateTime.Now.Ticks / 1000) - EQSETTINGS._LastEQTitle) < (EQSETTINGS._EQTitleShowTime * 10000))) { return(false); } } } catch { EQSETTINGS._EQDisplayTitle = false; EQSETTINGS._LastEQTitle = (DateTime.Now.Ticks / 1000); return(false); } int handle = -1; try { handle = g_Player.Player.CurrentAudioStream; } catch (Exception exception) { Log.Debug("MiniDisplay.GetEQ(): Caugth exception obtaining audio stream: {0}", new object[] { exception }); return(false); } if ((handle != 0) & (handle != -1)) { int num2; if (extensiveLogging) { Log.Info("MiniDisplay.GetEQ(): attempting to retrieve equalizer data from audio stream {0}", new object[] { handle }); } try { int num3; if (flag2) { num3 = -2147483630; } else { num3 = -2147483646; } num2 = Bass.BASS_ChannelGetData(handle, EQSETTINGS.EqFftData, num3); } catch { if (extensiveLogging) { Log.Info("MiniDisplay.GetEQ(): CAUGHT EXCeption - audio stream {0} disappeared", new object[] { handle }); } return(false); } if (num2 > 0) { return(true); } if (extensiveLogging) { Log.Info("MiniDisplay.GetEQ(): unable to retreive equalizer data"); } return(false); } if (extensiveLogging) { Log.Info("MiniDisplay.GetEQ(): Audio Stream not available"); } return(false); }
public bool GetFFTData(float[] fftDataBuffer) { return(_vizStream != null && Bass.BASS_ChannelGetData(_vizStream.Handle, fftDataBuffer, _maxFFT) > 0); }
public bool DownmixMogg(string CON_file, string output, MoggSplitFormat format, string quality, bool doWii = false, double start = 0.0, double length = 0.0, double fadeIn = 0.0, double fadeOut = 0.0, double volume = 0.0, string stems = "allstems") { if (!ExtractDecryptMogg(CON_file, true)) { return(false); } try { if (!InitBass()) { return(false); } var BassStream = Bass.BASS_StreamCreateFile(Tools.GetOggStreamIntPtr(), 0, Tools.PlayingSongOggData.Length, BASSFlag.BASS_STREAM_DECODE); var channel_info = Bass.BASS_ChannelGetInfo(BassStream); var BassMixer = BassMix.BASS_Mixer_StreamCreate(doWii ? 22050 : channel_info.freq, 2, BASSFlag.BASS_MIXER_END | BASSFlag.BASS_STREAM_DECODE); if (doWii) { BassMix.BASS_Mixer_StreamAddChannelEx(BassMixer, BassStream, BASSFlag.BASS_MIXER_MATRIX, 0, Bass.BASS_ChannelSeconds2Bytes(BassMixer, length)); var track_vol = (float)Utils.DBToLevel(Convert.ToDouble(volume), 1.0); Bass.BASS_ChannelSetPosition(BassStream, Bass.BASS_ChannelSeconds2Bytes(BassStream, start)); BASS_MIXER_NODE[] nodes = { new BASS_MIXER_NODE(0, 0), new BASS_MIXER_NODE(Bass.BASS_ChannelSeconds2Bytes(BassMixer, fadeIn), track_vol), new BASS_MIXER_NODE(Bass.BASS_ChannelSeconds2Bytes(BassMixer, length - fadeOut),track_vol), new BASS_MIXER_NODE(Bass.BASS_ChannelSeconds2Bytes(BassMixer, length), 0) }; BassMix.BASS_Mixer_ChannelSetEnvelope(BassStream, BASSMIXEnvelope.BASS_MIXER_ENV_VOL, nodes, nodes.Count()); } else { BassMix.BASS_Mixer_StreamAddChannel(BassMixer, BassStream, BASSFlag.BASS_MIXER_MATRIX); } var matrix = GetChannelMatrix(Parser.Songs[0], channel_info.chans, stems); BassMix.BASS_Mixer_ChannelSetMatrix(BassStream, matrix); var output_file = output; if (string.IsNullOrWhiteSpace(output)) { output_file = Path.GetDirectoryName(CON_file) + "\\" + Parser.Songs[0].InternalName + (format == MoggSplitFormat.WAV ? ".wav" : ".ogg"); } if (format == MoggSplitFormat.OGG) { var cmd = "bin\\oggenc2.exe -q" + quality + " - -o\"" + output_file + "\""; BassEnc.BASS_Encode_Start(BassMixer, cmd, BASSEncode.BASS_ENCODE_FP_24BIT | BASSEncode.BASS_ENCODE_AUTOFREE, null, IntPtr.Zero); } else { BassEnc.BASS_Encode_Start(BassMixer, output_file, BASSEncode.BASS_ENCODE_PCM | BASSEncode.BASS_ENCODE_AUTOFREE, null, IntPtr.Zero); } while (true) { var buffer = new byte[20000]; var c = Bass.BASS_ChannelGetData(BassMixer, buffer, buffer.Length); if (c < 0) { break; } } UnloadLibraries(); Tools.ReleaseStreamHandle(); return(File.Exists(output_file)); } catch (Exception ex) { ErrorLog.Add("Error downmixing mogg file:"); ErrorLog.Add(ex.Message); UnloadLibraries(); Tools.ReleaseStreamHandle(); return(false); } }
/// <summary> /// Determines if the stream contains frames with the specified syncwords. /// </summary> /// <param name="syncWord">Syncword to search for.</param> /// <returns></returns> private bool IsEncoded(SyncWord syncWord) { const int framesToCheck = 5; const int bytesPerSample = 4; const int bytesPerWord = 2; const int channelCount = 2; long streamLength = Bass.BASS_ChannelGetLength(_handle); long currentPosition = 0; if (streamLength > 0) { currentPosition = Bass.BASS_ChannelGetPosition(_handle); if (currentPosition != 0) { Bass.BASS_ChannelSetPosition(_handle, 0); } } SyncFifoBuffer syncFifoBuffer = new SyncFifoBuffer(syncWord); float[] readBuffer = new float[channelCount]; int lastSyncWordPosition = -1; int lastFrameSize = -1; int frameCount = 0; bool result = false; int sampleIndex = 0; int maxSampleIndex = (syncWord.MaxFrameSize / bytesPerWord) * framesToCheck + syncWord.WordLength; while (!result && sampleIndex < maxSampleIndex) { int bytesRead = Bass.BASS_ChannelGetData(_handle, readBuffer, readBuffer.Length * bytesPerSample); if (bytesRead <= 0) { // End of stream break; } int samplesRead = bytesRead / bytesPerSample; int readSample = 0; while (!result && readSample < samplesRead) { // Convert float value to word UInt16 word = (UInt16)(readBuffer[readSample] * 32768); // Add word to fifo buffer syncFifoBuffer.Write(word); // Check Sync word if (syncFifoBuffer.IsMatch()) { int newSyncWordPosition = (sampleIndex - syncWord.WordLength + 1) * bytesPerWord; if (lastSyncWordPosition != -1) { int thisFrameSize = newSyncWordPosition - lastSyncWordPosition; if (lastFrameSize != -1) { if (thisFrameSize != lastFrameSize) { break; } } lastFrameSize = thisFrameSize; frameCount++; } lastSyncWordPosition = newSyncWordPosition; result = (frameCount == framesToCheck); } sampleIndex++; readSample++; } } if (streamLength > 0) { Bass.BASS_ChannelSetPosition(_handle, currentPosition); } return(result); }
public void Evaluate(int SpreadMax) { bool reset = false; if (this.FPinInPath.PinIsChanged) { //Bass.BASS_StreamFree(this.FHandle); string path; this.FPinInPath.GetString(0, out path); if (File.Exists(path)) { int handle = Bass.BASS_StreamCreateFile(path, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN); if (handle < -1) { this.FHandle = handle; BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(this.FHandle); this.FNumChans = info.chans; this.FFileValid = true; } else { this.FFileValid = false; this.FHandle = -1; this.FPinOutLeft.SliceCount = 0; this.FPinOutRight.SliceCount = 0; this.FPinOutStatus.SetString(0, "Inavlid file format"); } } else { this.FFileValid = false; this.FHandle = -1; this.FPinOutLeft.SliceCount = 0; this.FPinOutRight.SliceCount = 0; this.FPinOutStatus.SetString(0, "File does not exist"); } reset = true; } if (this.FPinInInvidivual.PinIsChanged || this.FPinInSize.PinIsChanged || reset) { this.FFlag = this.GetDataType(); if (this.FFlag != -1) { this.FFlagValid = true; } else { this.FFlagValid = false; this.FPinOutLeft.SliceCount = 0; this.FPinOutRight.SliceCount = 0; this.FPinOutStatus.SetString(0, "FFT must be 256,512,1024,2048,4096 or 8192"); } reset = true; } if (this.FPinInPosition.PinIsChanged || reset) { if (this.FFlagValid && this.FFileValid) { double position; this.FPinInPosition.GetValue(0, out position); int len = this.FSize; if (!this.FIndividual || this.FNumChans == 1) { len = len / 2; } //byte[] buffer = new byte[len * 4]; float[] samples = new float[len]; Bass.BASS_ChannelSetPosition(this.FHandle, position); int cnt = Bass.BASS_ChannelGetData(this.FHandle, samples, this.GetDataType()); long pos = Bass.BASS_ChannelGetPosition(this.FHandle); double dpos = Bass.BASS_ChannelBytes2Seconds(this.FHandle, pos); //float[] samples = new float[len]; //GCHandle handle; //handle = GCHandle.Alloc(samples, GCHandleType.Pinned); //Marshal.Copy(samples, 0, handle.AddrOfPinnedObject(), buffer.Length); //handle.Free(); this.FPinOutPosition.SetValue(0, dpos); this.FPinOutStatus.SetString(0, "OK"); if (this.FNumChans == 1 || !this.FIndividual) { this.FPinOutLeft.SliceCount = len; this.FPinOutRight.SliceCount = len; for (int i = 0; i < len; i++) { this.FPinOutLeft.SetValue(i, (double)samples[i]); this.FPinOutRight.SetValue(i, (double)samples[i]); } } else { this.FPinOutLeft.SliceCount = len / 2; this.FPinOutRight.SliceCount = len / 2; for (int i = 0; i < len; i++) { if (i % 2 == 0) { this.FPinOutLeft.SetValue(i / 2, (double)samples[i]); } else { this.FPinOutRight.SetValue(i / 2, (double)samples[i]); } } } } } }