Exemplo n.º 1
0
        private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            if (_deviceReady && _handle != 0)
            {
                Bass.BASS_ChannelGetData(_handle, _frequenciesValues, (int)BASSData.BASS_DATA_FFT512);
                OnFrequencesBandChanged(new FrequencesBandChangedEventHandlerArgs
                { FrequencesBand = _frequenciesValues.Select(f => f * 1000).ToArray() });

                long bytePosition = Bass.BASS_ChannelGetPosition(_handle);

                int level = Bass.BASS_ChannelGetLevel(_handle); ;
                LeftChannelValue = Utils.LowWord32(level); // the left level
                RightChannelValue = Utils.HighWord32(level); // the right level
               
                OnChannelVolumeInfoChanged(new ChannelVolumeInfoChangedEventHandlerArgs()
                {
                    RightChannelValue = RightChannelValue,
                    LeftChannelVolume = LeftChannelValue
                });

                int position = (int)Bass.BASS_ChannelBytes2Seconds(_handle, bytePosition);
                if (_currentPosition < position)
                {
                    _currentPosition = position;
                    OnTrackPositionProgressChanged(new TrackPositionProgrressChangedEventHandlerArgs()
                    {
                        PositionSeconds = _currentPosition
                    });
                }
            }
        }
Exemplo n.º 2
0
        public void FFT()
        {
            if (playing)
            {
                int      length = (int)(sizeof(float) * 256);
                float[]  data   = new float[256];
                GCHandle hGC    = GCHandle.Alloc(data, GCHandleType.Pinned);
                length = Bass.BASS_ChannelGetData(stream, hGC.AddrOfPinnedObject(), (int)BASSData.BASS_DATA_FFT256);
                int level = (Bass.BASS_ChannelGetLevel(stream) >> 16) & 0x0000FFFF;

                float fres = data[(int)(length * 200 / 44100)] + data[(int)(length * 150 / 44100)] + data[(int)(length * 100 / 44100)];
                fres /= 3;
                hGC.Free();
                Lb.Content = fres.ToString();
                //if (fres > oldvalue) oldvalue = fres;
                //Lb.Content = oldvalue.ToString();
                if (!float.IsNaN(fres))
                {
                    TimeS1.Value = Math.Abs((double)level / 32768.0) * 10;
                    double red   = (fres * 255) * 3;
                    Color  color = new Color()
                    {
                        R = (Byte)(255 - red),
                        G = (Byte)(255 - red),
                        B = (Byte)(255 - red),
                        A = 255
                    };
                    Rect.Fill = new System.Windows.Media.SolidColorBrush(color);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Gets the current volume levels.
        /// </summary>
        /// <returns>A VolumeLevels object containing the left and right volume levels (0 - 32768)</returns>
        public VolumeLevels GetVolumeLevels()
        {
            var levels = new VolumeLevels();
            var level  = Bass.BASS_ChannelGetLevel(ChannelId);

            levels.Left  = Utils.LowWord32(level);
            levels.Right = Utils.HighWord32(level);
            return(levels);
        }
Exemplo n.º 4
0
        public bool GetChannelLevel(out double dbLevelL, out double dbLevelR)
        {
            dbLevelL = 0;
            dbLevelR = 0;
            if (_vizStream == null)
            {
                return(false);
            }
            var level = Bass.BASS_ChannelGetLevel(_vizStream.Handle);

            dbLevelL = Un4seen.Bass.Utils.LevelToDB(Un4seen.Bass.Utils.LowWord32(level), 65535);  // the left level
            dbLevelR = Un4seen.Bass.Utils.LevelToDB(Un4seen.Bass.Utils.HighWord32(level), 65535); // the right level
            return(true);
        }
Exemplo n.º 5
0
        public int GetSoundLevel()
        {
            float[] level = new float[2];
            //Bass.BASS_ChannelGetLevel()

            if (BufferLength() > 0 && Bass.BASS_ChannelGetLevel(RecordChannel, level))
            {
                return((int)((level[0] + level[1]) * MaxLevel / 2));
            }
            else
            {
                return(-1);
            }
        }
Exemplo n.º 6
0
        private void timerUpdate_Tick(object sender, EventArgs e)
        {
            int level = Bass.BASS_ChannelGetLevel(_mixer);

            progressBarLeft.Value  = Utils.LowWord32(level);
            progressBarRight.Value = Utils.HighWord32(level);

            if (_currentTrack != null)
            {
                long pos = BassMix.BASS_Mixer_ChannelGetPosition(_currentTrack.Channel);
                labelTime.Text   = Utils.FixTimespan(Bass.BASS_ChannelBytes2Seconds(_currentTrack.Channel, pos), "HHMMSS");
                labelRemain.Text = Utils.FixTimespan(Bass.BASS_ChannelBytes2Seconds(_currentTrack.Channel, _currentTrack.TrackLength - pos), "HHMMSS");

                DrawWavePosition(pos, _currentTrack.TrackLength);
            }
        }
Exemplo n.º 7
0
        void _timer_Tick(object sender, EventArgs e)
        {
            rectangleWidth = (int)this.bglbar.ActualWidth;

            if (stream != 0)
            {
                int level = 0;

                level = Bass.BASS_ChannelGetLevel(stream);

                int left  = Utils.LowWord32(level);  // the left level
                int right = Utils.HighWord32(level); // the right level

                this.lbar.Width = rectangleWidth * left >> 15;
                this.rbar.Width = rectangleWidth * right >> 15;
            }
        }
Exemplo n.º 8
0
        public static List <int> GetSoundWave(string file)
        {
            int        amplitude    = 0;
            List <int> volumeStream = new List <int>();
            int        channel      = Bass.BASS_StreamCreateFile(file, 0, 0, BASSFlag.BASS_STREAM_DECODE);

            while (amplitude != -1)
            {
                amplitude = Bass.BASS_ChannelGetLevel(channel);

                int left  = Utils.LowWord32(amplitude);
                int right = Utils.HighWord32(amplitude);

                volumeStream.Add(left + right);
            }

            Bass.BASS_StreamFree(channel);
            return(volumeStream);
        }
Exemplo n.º 9
0
        void timer_Tick(object sender, EventArgs e)
        {
            var level = Bass.BASS_ChannelGetLevel(stream);
            var left  = Utils.LowWord32(level) / (double)Int16.MaxValue;
            var right = Utils.HighWord32(level) / (double)Int16.MaxValue;

            var diff = 200 * (left + right) - currentItem.VuValue;

            if (diff > 0)
            {
                currentItem.VuValue += diff / 10d;
            }
            else
            {
                currentItem.VuValue += diff / 20d;
            }

            currentItem.Time = TimeSpan.FromSeconds(
                Bass.BASS_ChannelBytes2Seconds(stream,
                                               Bass.BASS_ChannelGetPosition(stream)));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Finds sections of silence in a sound stream.
        /// </summary>
        /// <param name="file">Filename for the sound stream.</param>
        /// <param name="block">The block of time of a sample to get the level (peak amplitude), default is 20 miliseconds.</param>
        /// <param name="silence">The silence time to split by default is 2000 miliseconds (2 seconds).</param>
        /// <param name="minGap">The minimum time for the splits, default is 480000 miliseconds (8 mins).</param>
        /// <param name="bgWorker">The BackgroundWorker to report progress.</param>
        /// <returns>List of sound files</returns>
        public static List <SoundFile> FindSilence(string file, float block = 20, float silence = 2000, float minGap = 480000, BackgroundWorker bgWorker = null)
        {
            int   level        = 0;
            int   count        = 0;
            float gap          = 0;
            float start        = 0;
            float position     = block;
            var   buffer       = new IntPtr();
            var   sounds       = new List <SoundFile>();
            var   volumeStream = new List <int>();

            var chan = Bass.BASS_StreamCreateFile(file, 0, 0, BASSFlag.BASS_STREAM_DECODE);
            var len  = Bass.BASS_ChannelSeconds2Bytes(chan, block / (float)1000 - (float)0.02);

            while ((level = Bass.BASS_ChannelGetLevel(chan)) != -1)
            {
                int left  = Utils.LowWord32(level);
                int right = Utils.HighWord32(level);
                volumeStream.Add(left + right);
                if (((count = ((left + right) < 40000) ? count + 1 : 0) == silence / block) && (gap > minGap))
                {
                    var pos   = (int)Math.Round(position / 1000);
                    var sound = new SoundFile($"File_{pos}", start / 1000.0, position / 1000.0);
                    bgWorker?.ReportProgress(pos, sound);
                    start = position + 1;
                    sounds.Add(sound);
                    gap = 0;
                }
                else if (position % 50000 == 0)
                {
                    bgWorker?.ReportProgress((int)Math.Round(position / 1000), volumeStream);
                }
                Bass.BASS_ChannelGetData(chan, buffer, (int)len);
                position += block;
                gap      += block;
            }
            Bass.BASS_StreamFree(chan);
            return(sounds);
        }
Exemplo n.º 11
0
 private void AnalyzeOggs(IEnumerable <string> oggs)
 {
     Log("Analyzing ogg files and deleting silent files");
     Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);
     foreach (var ogg in oggs)
     {
         var BassStream = Bass.BASS_StreamCreateFile(ogg, 0, 0, BASSFlag.BASS_STREAM_DECODE);
         var level      = new float[1];
         while (Bass.BASS_ChannelGetLevel(BassStream, level, 1, BASSLevel.BASS_LEVEL_MONO))
         {
             if (level[0] != 0)
             {
                 break;
             }
         }
         Bass.BASS_StreamFree(BassStream);
         if (level[0] == 0)
         {
             Tools.DeleteFile(ogg);
         }
     }
     Bass.BASS_Free();
 }
Exemplo n.º 12
0
        public static void OutputStream(string file)
        {
            float block = 20;
            var   chan  = Bass.BASS_StreamCreateFile(file, 0, 0, BASSFlag.BASS_STREAM_DECODE);
            var   len   = Bass.BASS_ChannelSeconds2Bytes(chan, block / (float)1000 - (float)0.02);

            int level  = 0;
            var buffer = new IntPtr();
            var data   = new List <int>();

            while (-1 != (level = Bass.BASS_ChannelGetLevel(chan)))
            {
                data.Add(level);
                Bass.BASS_ChannelGetData(chan, buffer, (int)len);
            }
            Bass.BASS_StreamFree(chan);

            double max = data.Max();

            foreach (var item in data)
            {
                OutputLevel(item, max);
            }
        }
Exemplo n.º 13
0
        private void waveformGenerateWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            WaveformGenerationParams waveformParams = e.Argument as WaveformGenerationParams;
            int  stream         = Bass.BASS_StreamCreateFile(waveformParams.Path, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
            int  frameLength    = (int)Bass.BASS_ChannelSeconds2Bytes(stream, 0.02);
            long streamLength   = Bass.BASS_ChannelGetLength(stream, 0);
            int  frameCount     = (int)(streamLength / (double)frameLength);
            int  waveformLength = frameCount * 2;

            float[] waveformData = new float[waveformLength];
            float[] levels       = new float[2];

            int actualPoints = Math.Min(waveformParams.Points, frameCount);

            int compressedPointCount = actualPoints * 2;

            float[]    waveformCompressedPoints = new float[compressedPointCount];
            List <int> waveMaxPointIndexes      = new List <int>();

            for (int i = 1; i <= actualPoints; i++)
            {
                waveMaxPointIndexes.Add((int)Math.Round(waveformLength * (i / (double)actualPoints), 0));
            }

            float maxLeftPointLevel  = float.MinValue;
            float maxRightPointLevel = float.MinValue;
            int   currentPointIndex  = 0;

            for (int i = 0; i < waveformLength; i += 2)
            {
                Bass.BASS_ChannelGetLevel(stream, levels, 0.02f, BASSLevel.BASS_LEVEL_STEREO);
                waveformData[i]     = levels[0];
                waveformData[i + 1] = levels[1];

                if (levels[0] > maxLeftPointLevel)
                {
                    maxLeftPointLevel = levels[0];
                }
                if (levels[1] > maxRightPointLevel)
                {
                    maxRightPointLevel = levels[1];
                }

                if (i > waveMaxPointIndexes[currentPointIndex])
                {
                    waveformCompressedPoints[(currentPointIndex * 2)]     = maxLeftPointLevel;
                    waveformCompressedPoints[(currentPointIndex * 2) + 1] = maxRightPointLevel;
                    maxLeftPointLevel  = float.MinValue;
                    maxRightPointLevel = float.MinValue;
                    currentPointIndex++;
                }
                if (i % 3000 == 0)
                {
                    float[] clonedData = (float[])waveformCompressedPoints.Clone();
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        WaveformData = clonedData;
                    }));
                }

                if (waveformGenerateWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;;
                }
            }
            float[] finalClonedData = (float[])waveformCompressedPoints.Clone();
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                fullLevelData = waveformData;
                WaveformData  = finalClonedData;
            }));
            Bass.BASS_StreamFree(stream);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Detects waveform levels.
        /// </summary>
        private async Task DetectWaveformLevelsInnerAsync()
        {
            // Create progress reporter.
            IProgress <ProgressChangedEventArgs> prog = new Progress <ProgressChangedEventArgs>(value =>
            {
                // Invoke ProgressChanged event.
                if (ProgressChanged != null)
                {
                    ProgressChanged(this, value);
                }

                // Restart stopwatch.
                progressSw.Restart();
            });

            try
            {
                await Task.Run(() =>
                {
                    for (int i = 0; i < NumFrames; i++)
                    {
                        cts.Token.ThrowIfCancellationRequested();

                        // Get left and right levels.
                        float[] levels = new float[2];
                        //float[] fft = new float[4096];
                        Bass.BASS_ChannelGetLevel(stream, levels, 0.01f, BASSLevel.BASS_LEVEL_STEREO);
#if DEBUG
                        //Console.WriteLine($"Position of the playback after getlevel: {Bass.BASS_ChannelGetPosition(stream)}");
#endif
                        //Bass.BASS_ChannelGetData(stream, fft, (int)BASSData.BASS_DATA_FFT4096);
#if DEBUG
                        //Console.WriteLine($"Position of the playback after getdata: {Bass.BASS_ChannelGetPosition(stream)}");
#endif
                        float leftLevel  = levels[0];
                        float rightLevel = levels[1];

                        // Update left and right levels.
                        leftLevelList.Add(leftLevel);
                        rightLevelList.Add(rightLevel);

                        // Update peak value.
                        PeakValue = Math.Max(Math.Max(PeakValue, leftLevel), rightLevel);

                        // Increment frame done count.
                        FrameDoneCount++;

                        PercentageCompleted = 100f * FrameDoneCount / NumFrames;

                        if (progressSw.ElapsedMilliseconds >= 1)
                        {
                            if (ProgressPercentageInterval == 0f ||
                                Math.Floor(PercentageCompleted / ProgressPercentageInterval) > Math.Floor(lastProgressPercentageEventRaised / ProgressPercentageInterval))
                            {
                                progressSw.Reset();
                                lastProgressPercentageEventRaised = PercentageCompleted;
                                prog.Report(new ProgressChangedEventArgs(FrameDoneCount, PercentageCompleted));
                            }
                        }
                    }
                    // ~~ Completed. Identify the volume spurts next
                    VolumeSpurts = this.FindAllVolumeSpurts();
                }, cts.Token);
            }
            catch (OperationCanceledException)
            {
                // Do nothing.
            }
            catch (Exception)
            {
                // Do nothing.
            }
        }
Exemplo n.º 15
0
        private void GenerateWaveformData(string path, int points = waveformCompressedPointCount)
        {
            if (generateWaveCancelTokenSource != null && !generateWaveCancelTokenSource.IsCancellationRequested)
            {
                generateWaveCancelTokenSource.Cancel();
            }
            generateWaveCancelTokenSource = new CancellationTokenSource();

            Task.Run(() =>
            {
                int stream         = Bass.BASS_StreamCreateFile(path, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
                int frameLength    = (int)Bass.BASS_ChannelSeconds2Bytes(stream, 0.02);
                long streamLength  = Bass.BASS_ChannelGetLength(stream, 0);
                int frameCount     = (int)(streamLength / (double)frameLength);
                int waveformLength = frameCount * 2;
                float[] waveform   = new float[waveformLength];
                float[] levels     = new float[2];

                int actualPoints = Math.Min(points, frameCount);

                int compressedPointCount         = actualPoints * 2;
                float[] waveformCompressedPoints = new float[compressedPointCount];
                List <int> waveMaxPointIndexes   = new List <int>();
                for (int i = 1; i <= actualPoints; i++)
                {
                    waveMaxPointIndexes.Add((int)Math.Round(waveformLength * (i / (double)actualPoints), 0));
                }

                float maxLeftPointLevel  = float.MinValue;
                float maxRightPointLevel = float.MinValue;
                int currentPointIndex    = 0;
                for (int i = 0; i < waveformLength; i += 2)
                {
                    Bass.BASS_ChannelGetLevel(stream, levels);
                    waveform[i]     = levels[0];
                    waveform[i + 1] = levels[1];

                    if (levels[0] > maxLeftPointLevel)
                    {
                        maxLeftPointLevel = levels[0];
                    }
                    if (levels[1] > maxRightPointLevel)
                    {
                        maxRightPointLevel = levels[1];
                    }

                    if (i > waveMaxPointIndexes[currentPointIndex])
                    {
                        waveformCompressedPoints[(currentPointIndex * 2)]     = maxLeftPointLevel;
                        waveformCompressedPoints[(currentPointIndex * 2) + 1] = maxRightPointLevel;
                        maxLeftPointLevel  = float.MinValue;
                        maxRightPointLevel = float.MinValue;
                        currentPointIndex++;
                    }
                    if (i % 3000 == 0)
                    {
                        float[] clonedData = (float[])waveformCompressedPoints.Clone();
                        if (MainDispatcher == null)
                        {
                            WaveformData = clonedData;
                        }
                        else
                        {
                            MainDispatcher.Invoke(() => { WaveformData = clonedData; });
                        }
                    }
                    if (generateWaveCancelTokenSource.IsCancellationRequested)
                    {
                        break;
                    }
                }
                float[] finalClonedData = (float[])waveformCompressedPoints.Clone();
                if (MainDispatcher == null)
                {
                    FullLevelData = waveform;
                    WaveformData  = finalClonedData;
                }
                else
                {
                    MainDispatcher.Invoke(() =>
                    {
                        FullLevelData = waveform;
                        WaveformData  = finalClonedData;
                    });
                }
                Bass.BASS_StreamFree(stream);
            }, generateWaveCancelTokenSource.Token);
        }
Exemplo n.º 16
0
 public bool GetChannelLevels(ref float[] levels, float length)
 {
     return(Bass.BASS_ChannelGetLevel(audioHandle, levels, length, BASSLevel.BASS_LEVEL_STEREO));
 }
Exemplo n.º 17
0
 private void timer_Tick(object sender, EventArgs e)
 {
     label1.Content = TimeSpan.FromSeconds(BassUses.GetPosOfStream(BassUses.Stream)).ToString();
     slTime.Value   = BassUses.GetPosOfStream(BassUses.Stream);
     int level = Bass.BASS_ChannelGetLevel(_mixer);
 }
Exemplo n.º 18
0
    void loadData()
    {
        if (filepath != string.Empty && File.Exists(filepath))
        {
#if BASS_AUDIO
            long        trackLengthInBytes = Bass.BASS_ChannelGetLength(handle);
            const float FRAME_TIME         = 0.002f;
            long        frameLengthInBytes = Bass.BASS_ChannelSeconds2Bytes(handle, FRAME_TIME);
            int         NumFrames          = (int)System.Math.Round(1f * trackLengthInBytes / frameLengthInBytes);

            _data = new float[NumFrames * 2];

            float[] levels = new float[2];
            for (int i = 0; i < _data.Length && !stop; i += 2)
            {
                Bass.BASS_ChannelGetLevel(handle, levels, FRAME_TIME, BASSLevel.BASS_LEVEL_STEREO);
                float average = (levels[0] + levels[1]) / 2.0f;
                _data[i]     = -average;
                _data[i + 1] = average;
            }
#else
            byte[]  bytes      = File.ReadAllBytes(filepath);
            float[] sampleData = new float[0];
            switch (Path.GetExtension(filepath))
            {
            case (".ogg"):
                NVorbis.VorbisReader vorbis = new NVorbis.VorbisReader(filepath);
                vorbis.ClipSamples = false;

                _data = new float[vorbis.TotalSamples * vorbis.Channels];

                //vorbis.ReadSamples(_data, 0, _data.Length);

                int count = 0;
                while ((count += vorbis.ReadSamples(_data, count, 16000)) > 0 && !stop)
                {
                }

                break;

            case (".wav"):
                WAV wav = new WAV(bytes);
                sampleData = NAudioPlayer.InterleaveChannels(wav);
                break;

            case (".mp3"):
                NAudioPlayer.WAVFromMp3Data(bytes, out sampleData);
                break;

            default:
                return;
            }
#endif
            if (!stop)
            {
#if !BASS_AUDIO
                _data = sampleData;
#endif

                Debug.Log("Sample length: " + _data.Length);
            }
            else
            {
                _data = new float[0];
            }
        }
    }