Пример #1
0
        public void OpenFile(string path)
        {
            // BASS_STREAM_PRESCAN = Pre-scan the file for accurate seek points and length reading in MP3/MP2/MP1 files
            // and chained OGG files (has no effect on normal OGG files). This can significantly increase the time taken to create the stream, particularly with a large file and/or slow storage media.

            // BASS_SAMPLE_FLOAT = Use 32-bit floating-point sample data.
            //int stream = Bass.BASS_StreamCreateFile(path, 0L, 0L, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
            _playingStream = Bass.BASS_StreamCreateFile(path, 0L, 0L, BASSFlag.BASS_DEFAULT);

            if (_playingStream != 0)
            {
                var info = Bass.BASS_ChannelGetInfo(_playingStream);

                sampleRate    = info.freq;
                bitsPerSample = info.Is8bit ? 8 : (info.Is32bit ? 32 : 16);
                channels      = info.chans;

                duration = Bass.BASS_ChannelBytes2Seconds(_playingStream, Bass.BASS_ChannelGetLength(_playingStream));
                CanPlay  = true;
            }
            else
            {
                CanPlay = false;
            }
        }
Пример #2
0
        public override int GetFormat(int nHandle, ref CWin32.WAVEFORMATEX wfx)
        {
            var chinfo = Bass.BASS_ChannelGetInfo(stream_in);

            _wfx.wFormatTag      = 1;                                           // 1 == PCM
            _wfx.nChannels       = (ushort)chinfo.chans;                        //
            _wfx.nSamplesPerSec  = (uint)chinfo.freq;                           //
            _wfx.nAvgBytesPerSec = (uint)(chinfo.freq * 2 * chinfo.chans);      //
            _wfx.nBlockAlign     = (ushort)(2 * chinfo.chans);                  // 16bit * mono/stereo
            _wfx.wBitsPerSample  = 16;

            //Debug.WriteLine("**WAVEFORMATEX** in Cmp3.cs from stream info");
            //Debug.WriteLine("wFormatTag=      " + 1);
            //Debug.WriteLine("nChannels =      " + chinfo.chans.ToString("X4"));
            //Debug.WriteLine("nSamplesPerSec=  " + chinfo.freq.ToString("X8"));
            //Debug.WriteLine("nAvgBytesPerSec= " + (chinfo.freq * 4).ToString("X8"));
            //Debug.WriteLine("nBlockAlign=     " + (2 * chinfo.chans).ToString("X4"));
            //Debug.WriteLine("wBitsPerSample=  " + (16).ToString("X4"));

            wfx = _wfx;

            #region [ Debug info ]
            //Debug.WriteLine("**WAVEFORMATEX** in Cmp3.cs from binary array");
            //Debug.WriteLine("wFormatTag=      " + wfx.wFormatTag.ToString("X4"));
            //Debug.WriteLine("nChannels =      " + wfx.nChannels.ToString("X4"));
            //Debug.WriteLine("nSamplesPerSec=  " + wfx.nSamplesPerSec.ToString("X8"));
            //Debug.WriteLine("nAvgBytesPerSec= " + wfx.nAvgBytesPerSec.ToString("X8"));
            //Debug.WriteLine("nBlockAlign=     " + wfx.nBlockAlign.ToString("X4"));
            //Debug.WriteLine("wBitsPerSample=  " + wfx.wBitsPerSample.ToString("X4"));
            //Debug.WriteLine("cbSize=          " + wfx.cbSize.ToString("X4"));
            #endregion

            return(0);
        }
Пример #3
0
    BASSTimer timerBPM            = new BASSTimer(20);         //New instance of a timer from the Bass Lib (interval for a Tick event 20ms)

    // Start is called before the first frame update
    void Start()
    {
        if (Bass.BASS_RecordInit(-1))                 //If the default device(-1) is initializaed successfully
        {
            Debug.Log("Device initialized");          //Tell that the device can be used
            _myRecProc = new RECORDPROC(MyRecording); //Set _myRecProc as the code from MyRecording

            //Get channel handle (Record at samplerate,with num of channels,Start the recording paused,User instance data to pass to the callback function)
            recHandle = Bass.BASS_RecordStart(44100, 2, BASSFlag.BASS_RECORD_PAUSE, _myRecProc, IntPtr.Zero); //start recording but paused AND set recHandle = to recording's handle
            Bass.BASS_ChannelPlay(recHandle, false);                                                          //resume playback of (recHandle,don't restart from beggining)
            Debug.Log("recHandle:" + recHandle.ToString());                                                   //Show the handle ID

            //get samplerate
            BASS_CHANNELINFO info = new BASS_CHANNELINFO();                             //create a new info instance
            Bass.BASS_ChannelGetInfo(recHandle, info);                                  //Retrieve info of the channel (channel to get info from, where to store info)
            Debug.Log("Channels: " + info.chans.ToString() + " Freq: " + info.freq.ToString());
            if (Bass.BASS_ChannelIsActive(recHandle) == BASSActive.BASS_ACTIVE_PLAYING) //Check if the channel is active
            {
                Debug.Log("The Channel is playing/recording");
            }
            timerBPM.Tick += timerBPM_Tick;     //Define the callback function for the timer
            //if I have a got a recHandle && the playback status of the recHandle is successful
            if (recHandle != 0 && Bass.BASS_ChannelPlay(recHandle, false))
            {
                _bpm.Reset(info.freq);      //set bpm  frequency to the one retrieved from the channel
                this.timerBPM.Start();      //Start the timer
            }
        }
        else
        {
            Debug.Log("Device could not be initialized");   //Tell that the operation failed
        }
    }
Пример #4
0
        public void LoadMusic(string musicPath)
        {
            //释放之前的
            Stop();
            Bass.BASS_StreamFree(CurrentMusicHandle);

            switch (MusicHelper.GetMusicType(musicPath))
            {
            case MusicHelper.MusicType.MOD:
                //MOD音乐获取长度要求在BASS_MusicLoad(String,Int64,Int32,BASSFlag,Int32)调用中使用BASS_MUSIC_PRESCAN标志
                //BASS_MusicLoad 用来加载MOD音乐文件-MO3 / IT / XM / S3M / MTM / MOD / UMX格式。
                //方法说明:文件路径   偏移   数据长度 0使用所有数据
                CurrentMusicHandle = Bass.BASS_MusicLoad(musicPath, 0L, 0, BASSFlag.BASS_MUSIC_PRESCAN, 0);
                break;

            case MusicHelper.MusicType.Stream:
                //BASS_StreamCreateFile 用来加载MP3,MP2,MP1,OGG,WAV,AIFF或插件支持的文件创建示例流
                CurrentMusicHandle = Bass.BASS_StreamCreateFile(musicPath, 0L, 0, BASSFlag.BASS_DEFAULT);
                break;

            case MusicHelper.MusicType.None:
                Debug.LogError("check file");
                return;
            }
            Play();
            BASS_CHANNELINFO info      = Bass.BASS_ChannelGetInfo(CurrentMusicHandle);
            BASSError        bASSError = Bass.BASS_ErrorGetCode();

            Debug.Log($"Load Music Success!!! \ncurrentMusicHandle:{CurrentMusicHandle}\nTotletime(s):{GetMusicTotleTime()}\nInfo:{info.ToString()}\nerror:{bASSError}\n\n");
        }
Пример #5
0
        public override int Open(string filename)
        {
            bool r = Bass.BASS_Init(0, 48000, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);

            stream_in = Bass.BASS_StreamCreateFile(filename, 0, 0, BASSFlag.BASS_DEFAULT | BASSFlag.BASS_STREAM_DECODE);
            // BASS_DEFAULT: output 32bit (16bit stereo)
            if (stream_in == 0)
            {
                BASSError be = Bass.BASS_ErrorGetCode();
                Trace.TraceInformation("Cmp3ogg: StreamCreateFile error: " + be.ToString());
            }
            nTotalPCMSize = Bass.BASS_ChannelGetLength(stream_in);

            #region [ Getting WAVEFORMEX info ]
            var chinfo = Bass.BASS_ChannelGetInfo(stream_in);
            wfx = new CWin32.WAVEFORMATEX(
                (ushort)1,                                              // wFormatTag
                (ushort)chinfo.chans,                                   // nChannels
                (uint)chinfo.freq,                                      // nSamplesPerSec
                (uint)(chinfo.freq * 2 * chinfo.chans),                 // nAvgBytesPerSec
                (ushort)(2 * chinfo.chans),                             // nBlockAlign
                16,                                                     // wBitsPerSample
                0                                                       // cbSize
                );
            #endregion

            //string fn = Path.GetFileName(filename);
            //Trace.TraceInformation("filename=" + fn + ", size=(decode): " + wavdata.Length + ", channelgetlength=" + _TotalPCMSize2 + ", " + _TotalPCMSize) ;

            return(0);
        }
Пример #6
0
        protected override void SetData(float[] samples)
        {
            BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(this.FChannel.BassHandle.Value);
            int len = samples.Length;

            this.FPinOutLeft.SliceCount  = len / 2;
            this.FPinOutRight.SliceCount = len / 2;
            if (info.chans > 1)
            {
                //Note: Change that to make sure it Goes with any channel soundtrack.
                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]);
                    }
                }
            }
            else
            {
                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]);
                }
            }
        }
Пример #7
0
        public static float[] BASS_Mixer_ChannelGetLevel(int handle, float length = 0.02f, BASSLevel flags = BASSLevel.BASS_LEVEL_ALL)
        {
            BASS_CHANNELINFO bass_CHANNELINFO = Bass.BASS_ChannelGetInfo(handle);

            if (bass_CHANNELINFO == null)
            {
                return(null);
            }
            int num = bass_CHANNELINFO.chans;

            if ((flags & BASSLevel.BASS_LEVEL_MONO) == BASSLevel.BASS_LEVEL_MONO)
            {
                num = 1;
            }
            else if ((flags & BASSLevel.BASS_LEVEL_STEREO) == BASSLevel.BASS_LEVEL_STEREO)
            {
                num = 2;
            }
            float[] array = new float[num];
            if (BassMix.BASS_Mixer_ChannelGetLevel(handle, array, length, flags))
            {
                return(array);
            }
            return(null);
        }
Пример #8
0
        private void GetChannelInfo(int channel)
        {
            if (channel == 0)
            {
                return;
            }
            if (!Bass.BASS_ChannelGetInfo(channel, this._channelInfo))
            {
                throw new ArgumentException("Invalid channel: " + Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode()));
            }
            this._samplerate = this._channelInfo.freq;
            this._numchans   = this._channelInfo.chans;
            if ((this._channelInfo.flags & BASSFlag.BASS_SAMPLE_MONO) != BASSFlag.BASS_DEFAULT)
            {
                this._numchans = 1;
            }
            this._bitwidth = 16;
            bool flag = Bass.BASS_GetConfig(BASSConfig.BASS_CONFIG_FLOATDSP) == 1;

            if ((this._channelInfo.flags & BASSFlag.BASS_SAMPLE_FLOAT) > BASSFlag.BASS_DEFAULT || flag)
            {
                this._bitwidth = 32;
                return;
            }
            if ((this._channelInfo.flags & BASSFlag.BASS_SAMPLE_8BITS) != BASSFlag.BASS_DEFAULT)
            {
                this._bitwidth = 8;
            }
        }
Пример #9
0
        /// <summary>
        /// Creates audio stream.
        /// Locks file.
        /// </summary>
        public void CreateStream()
        {
            if (!(State == ReadyState.Started || State == ReadyState.ClosedStream))
            {
                throw new InvalidOperationException("Not ready.");
            }

            // Create stream.
            stream = Bass.BASS_StreamCreateFile(filePath, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
            if (stream == 0)
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            // Set number of frames.
            long trackLengthInBytes = Bass.BASS_ChannelGetLength(stream);
            long frameLengthInBytes = Bass.BASS_ChannelSeconds2Bytes(stream, 0.01d);

            NumFrames = (int)Math.Round(1f * trackLengthInBytes / frameLengthInBytes);
#if DEBUG
            Console.WriteLine(stream);
            BASS_CHANNELINFO info = new BASS_CHANNELINFO();
            Bass.BASS_ChannelGetInfo(stream, info);
            Console.WriteLine(info.ToString());
            Console.WriteLine($"track length in bytes from waveformgenerator.cs: {trackLengthInBytes}");
            Console.WriteLine($"how many bytes in 20 ms from waveformgenerator.cs: {frameLengthInBytes}");
            Console.WriteLine($"NumFrames: {NumFrames}");
#endif

            // Change state.
            State = ReadyState.CreatedStream;
        }
Пример #10
0
        protected override void SetData(float[] samples)
        {
            int len = this.DataLength;

            BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(this.FChannel.BassHandle.Value);

            if (info.chans == 1 || !this.Individual)
            {
                this.FPinOutLeft.SliceCount  = len;
                this.FPinOutRight.SliceCount = len;
                for (int i = 0; i < len; i++)
                {
                    this.FPinOutLeft.SetValue(i, (double)samples[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]);
                    }
                }
            }
        }
Пример #11
0
        private void openStream(string url)
        {
            sound[PlayerController.MainChannel] = Bass.BASS_StreamCreateURL(url, 0, BASSFlag.BASS_STREAM_STATUS, null, IntPtr.Zero);

            tagInfo = new TAG_INFO(url);
            BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(sound[PlayerController.MainChannel]);

            // display buffering for MP3, OGG...
            while (true)
            {
                long len = Bass.BASS_StreamGetFilePosition(sound[PlayerController.MainChannel], BASSStreamFilePosition.BASS_FILEPOS_END);
                if (len == -1)
                {
                    break; // typical for WMA streams
                }
                // percentage of buffer filled
                float progress = (
                    Bass.BASS_StreamGetFilePosition(sound[PlayerController.MainChannel], BASSStreamFilePosition.BASS_FILEPOS_DOWNLOAD) -
                    Bass.BASS_StreamGetFilePosition(sound[PlayerController.MainChannel], BASSStreamFilePosition.BASS_FILEPOS_CURRENT)
                    ) * 100f / len;

                if (progress > 75f)
                {
                    break; // over 75% full, enough
                }

                //Application.DoEvents();
                System.Threading.Thread.Sleep(500);
            }
        }
Пример #12
0
        public WaveWriter(string fileName, int stream, bool rewrite)
        {
            this.FileName = fileName;
            BASS_CHANNELINFO bass_CHANNELINFO = new BASS_CHANNELINFO();

            if (Bass.BASS_ChannelGetInfo(stream, bass_CHANNELINFO))
            {
                if ((bass_CHANNELINFO.flags & BASSFlag.BASS_SAMPLE_FLOAT) != BASSFlag.BASS_DEFAULT)
                {
                    this.BitsPerSample = 32;
                }
                else if ((bass_CHANNELINFO.flags & BASSFlag.BASS_SAMPLE_8BITS) != BASSFlag.BASS_DEFAULT)
                {
                    this.BitsPerSample = 8;
                }
                else
                {
                    this.BitsPerSample = 16;
                }
                this.OrigResolution = this.BitsPerSample;
                this._numChannels   = bass_CHANNELINFO.chans;
                this._sampleRate    = bass_CHANNELINFO.freq;
                this.Initialize(rewrite);
                return;
            }
            throw new ArgumentException("Could not retrieve channel information!");
        }
Пример #13
0
        public static void GetAudioInformation(string filename)
        {
            float lFrequency = 0;
            float lVolume    = 0;
            float lPan       = 0;

            int stream = Bass.BASS_StreamCreateFile(filename, 0L, 0L, BASSFlag.BASS_STREAM_DECODE);

            // the info members will contain most of it...
            BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(stream);

            if (Bass.BASS_ChannelGetAttribute(stream, BASSAttribute.BASS_ATTRIB_VOL, ref lVolume))
            {
                System.Diagnostics.Debug.WriteLine("Volume: " + lVolume);
            }

            if (Bass.BASS_ChannelGetAttribute(stream, BASSAttribute.BASS_ATTRIB_PAN, ref lPan))
            {
                System.Diagnostics.Debug.WriteLine("Pan: " + lPan);
            }

            if (Bass.BASS_ChannelGetAttribute(stream, BASSAttribute.BASS_ATTRIB_FREQ, ref lFrequency))
            {
                System.Diagnostics.Debug.WriteLine("Frequency: " + lFrequency);
            }

            int nChannels = info.chans;

            System.Diagnostics.Debug.WriteLine("Channels: " + nChannels);

            int nSamplesPerSec = info.freq;

            System.Diagnostics.Debug.WriteLine("SamplesPerSec: " + nSamplesPerSec);
        }
Пример #14
0
    protected override AudioInfo GetInfo()
    {
        BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(handle);

        int lengthSamples = (int)Bass.BASS_ChannelGetLength(handle) / sizeof(float);

        return(new AudioInfo(lengthSamples, info.freq, info.chans));
    }
Пример #15
0
        public bool OpenFile(string path)
        {
            Stop();

            if (ActiveStreamHandle != 0)
            {
                Bass.BASS_StreamFree(ActiveStreamHandle);
            }

            if (File.Exists(path))
            {
                ActiveStreamHandle = Bass.BASS_StreamCreateFile(path, 0, 0, BASSFlag.BASS_DEFAULT);

                if (ActiveStreamHandle != 0)
                {
                    //Текущая частота для Аналогового спектра
                    BASS_CHANNELINFO info = new BASS_CHANNELINFO();
                    Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                    sampleFrequency = info.freq;

                    //Размер текущей композиции в секундах
                    StreamFileLength = Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle,
                                                                      Bass.BASS_ChannelGetLength(ActiveStreamHandle));
                    //Event Media Opened
                    MediaOpened(this, new EventArgs());

                    CanPlay = true;
                    return(true);
                }
                else
                {
                    ActiveStreamHandle = 0;
                    CanPlay            = false;
                }
            }

            MessageBox.Show("No file found at:\n " + path, "No file found!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            BassTrackVM.TracksList.RemoveAt(TrackListView.currentTrackIndex);

            /*
             *
             * Законсервировано до лучших времен
             *
             *
             * if(UserSettings.globalCurrentAccount != null)
             * {
             *  using (ApplicationContext db = new ApplicationContext())
             *  {
             *      PlaylistViewModel.CurrentPlaylist.PlaylistTracks = BassTrackVM.TracksList;
             *
             *          db.PlaylistSet.Update(PlaylistViewModel.CurrentPlaylist);
             *          db.SaveChanges();
             *
             *
             *  }
             * }*/
            return(false);
        }
Пример #16
0
        private void buttonPlay_Click(object sender, System.EventArgs e)
        {
            BassAsio.BASS_ASIO_Stop();
            BassAsio.BASS_ASIO_ChannelReset(false, -1, BASSASIOReset.BASS_ASIO_RESET_PAUSE | BASSASIOReset.BASS_ASIO_RESET_JOIN);
            Bass.BASS_StreamFree(_streamFX);
            if (_fileName != String.Empty)
            {
                // create the decoding stream
                _stream = Bass.BASS_StreamCreateFile(_fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT);
                if (_stream != 0)
                {
                    // now we create a Tempo channel (again a decoding one)...the actual playing channel
                    _streamFX = BassFx.BASS_FX_TempoCreate(_stream, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_FX_FREESOURCE | BASSFlag.BASS_SAMPLE_FLOAT);
                    if (_streamFX == 0)
                    {
                        MessageBox.Show(this, "Can't create FX stream!", Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode()));
                        return;
                    }

                    // now setup ASIO
                    myAsioProc = new ASIOPROC(AsioCallback);

                    // get the stream channel info
                    BASS_CHANNELINFO info = new BASS_CHANNELINFO();
                    Bass.BASS_ChannelGetInfo(_streamFX, info);
                    _originSampleRate = (float)info.freq;
                    this.button2.Text = _originSampleRate.ToString("0");
                    // enable 1st output channel...(0=first)
                    BassAsio.BASS_ASIO_ChannelEnable(false, 0, myAsioProc, new IntPtr(_streamFX));
                    // and join the next channels to it
                    for (int a = 1; a < info.chans; a++)
                    {
                        BassAsio.BASS_ASIO_ChannelJoin(false, a, 0);
                    }
                    // since we joined the channels, the next commands will applay to all channles joined
                    // so setting the values to the first channels changes them all automatically
                    // set the source format (float, as the decoding channel is)
                    BassAsio.BASS_ASIO_ChannelSetFormat(false, 0, BASSASIOFormat.BASS_ASIO_FORMAT_FLOAT);
                    // set the source rate
                    BassAsio.BASS_ASIO_ChannelSetRate(false, 0, (double)info.freq);
                    // try to set the device rate too (saves resampling)
                    BassAsio.BASS_ASIO_SetRate((double)info.freq);
                    // and start playing it...
                    // start output using default buffer/latency
                    if (!BassAsio.BASS_ASIO_Start(0))
                    {
                        MessageBox.Show(this, "Can't start ASIO output", Enum.GetName(typeof(BASSError), BassAsio.BASS_ASIO_ErrorGetCode()));
                    }
                    else
                    {
                        this.labelStatus.Text = "playing";
                        this.timerUpdate.Start();
                    }
                }
            }
        }
Пример #17
0
        public override async Task <(bool Changed, SongData song)> Execute(SongData song)
        {
            int stream = Bass.BASS_StreamCreateFile(song.FullFileName, 0, 0, BASSFlag.BASS_STREAM_DECODE);

            if (stream == 0)
            {
                log.Error("ReplayGain: Could not create stream for {0}. {1}", song.FullFileName, Bass.BASS_ErrorGetCode().ToString());
                return(false, song);
            }

            BASS_CHANNELINFO chInfo = Bass.BASS_ChannelGetInfo(stream);

            if (chInfo == null)
            {
                log.Error("ReplayGain: Could not get channel info for {0}. {1}", song.FullFileName, Bass.BASS_ErrorGetCode().ToString());
                return(false, song);
            }
            var trackGain = new TrackGain(chInfo.freq, 16);

            var leftSamples  = new List <int>();
            var rightSamples = new List <int>();

            var bufLen = 1024;
            var buf    = new short[bufLen];

            while (true)
            {
                int length = Bass.BASS_ChannelGetData(stream, buf, bufLen * sizeof(short));
                if (length == -1)
                {
                    break;
                }

                for (int i = 0; i < length / sizeof(short); i += 2)
                {
                    leftSamples.Add(Convert.ToInt32(buf[i]));
                    rightSamples.Add(Convert.ToInt32(buf[i + 1]));
                }
            }

            Bass.BASS_StreamFree(stream);

            trackGain.AnalyzeSamples(leftSamples.ToArray(), rightSamples.ToArray());

            _albumGain?.AppendTrackData(trackGain);

            double gain = Math.Round(trackGain.GetGain(), 2, MidpointRounding.ToEven);
            double peak = Math.Round(trackGain.GetPeak(), 2, MidpointRounding.ToEven);

            song.ReplayGainTrack     = gain.ToString(CultureInfo.InvariantCulture);
            song.ReplayGainTrackPeak = peak.ToString(CultureInfo.InvariantCulture);

            return(true, song);
        }
Пример #18
0
 void init_tag()
 {
     try
     {
         _tagInfo = new TAG_INFO(_url);
         BASS_CHANNELINFO info = Bass.BASS_ChannelGetInfo(_Stream);
         if (info.ctype == BASSChannelType.BASS_CTYPE_STREAM_WMA)
         {
             isWMA = true;
         }
     }
     catch (Exception ex) { System.Windows.MessageBox.Show(ex.ToString()); }
 }
Пример #19
0
        public bool OpenFile(string path)
        {
            Stop();

            if (ActiveStreamHandle != 0)
            {
                ClearRepeatRange();
                ChannelPosition = 0;
                Bass.BASS_StreamFree(ActiveStreamHandle);
            }

            if (System.IO.File.Exists(path))
            {
                // Create Stream
                FileStreamHandle = ActiveStreamHandle = Bass.BASS_StreamCreateFile(path, 0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
                ChannelLength    = Bass.BASS_ChannelBytes2Seconds(FileStreamHandle, Bass.BASS_ChannelGetLength(FileStreamHandle, 0));
                Bass.BASS_ChannelSetAttribute(ActiveStreamHandle, BASSAttribute.BASS_ATTRIB_MUSIC_VOL_CHAN, 1.0f);
                //FileTag = TagLib.File.Create(path);
                GenerateWaveformData(path);
                if (ActiveStreamHandle != 0)
                {
                    // Obtain the sample rate of the stream
                    BASS_CHANNELINFO info = new BASS_CHANNELINFO();
                    Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                    sampleFrequency = info.freq;

                    // Set the stream to call Stop() when it ends.
                    int syncHandle = Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                                                              BASSSync.BASS_SYNC_END,
                                                              0,
                                                              endTrackSyncProc,
                                                              IntPtr.Zero);

                    if (syncHandle == 0)
                    {
                        throw new ArgumentException("Error establishing End Sync on file stream.", "path");
                    }

                    CanPlay = true;
                    return(true);
                }
                else
                {
                    ActiveStreamHandle = 0;
                    //FileTag = null;
                    CanPlay = false;
                }
            }
            return(false);
        }
Пример #20
0
        private void pictureBox1_Click(object sender, System.EventArgs e)
        {
            if (_Stream == 0 || Bass.BASS_ChannelIsActive(_Stream) != BASSActive.BASS_ACTIVE_PLAYING)
            {
                // not playing anymore...
                return;
            }
            BASS_CHANNELINFO info = new BASS_CHANNELINFO();

            if (Bass.BASS_ChannelGetInfo(_Stream, info))
            {
                _bpm.Reset(info.freq);
            }
        }
Пример #21
0
        public void getType()
        {
            BASS_CHANNELINFO info = new BASS_CHANNELINFO();

            Bass.BASS_ChannelGetInfo(_stream, info); // get info
            Debug.WriteLine(info.freq);
            LabelRate.Text = info.freq + " kHZ";
            switch (info.ctype)
            {
            case BASSChannelType.BASS_CTYPE_STREAM_MP3:
                btnCopyFile.Text = "拷贝MP3文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_MF:
                btnCopyFile.Text = "拷贝FLAC文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_OGG:
                btnCopyFile.Text = "拷贝OGG文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_AAC:
                btnCopyFile.Text = "拷贝ACC文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_WAV:
                btnCopyFile.Text = "拷贝WAV文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_WMA:
                btnCopyFile.Text = "拷贝WMA文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_APE:
                btnCopyFile.Text = "拷贝APE文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_FLAC:
                btnCopyFile.Text = "拷贝FLAC文件到";
                break;

            case BASSChannelType.BASS_CTYPE_STREAM_CD:
                btnCopyFile.Text = "拷贝CD文件到";
                break;

            default:
                btnCopyFile.Text = "拷贝未知格式文件到";
                break;
            }
        }
Пример #22
0
        private void buttonPlay_Click(object sender, System.EventArgs e)
        {
            this.label1.Text = "";
            Bass.BASS_StreamFree(_Stream);
            this.timerBPM.Stop();

            // test PlugIns...
            // after additional Add-Ons have been loaded,
            // they will be supported in the standard BASS_StreamCreateFile methods
            if (_FileName != String.Empty)
            {
                // create the stream
                _Stream = Bass.BASS_StreamCreateFile(_FileName, 0, 0, BASSFlag.BASS_DEFAULT);

                // update the tags
                _tagInfo = new TAG_INFO(_FileName);
                if (BassTags.BASS_TAG_GetFromFile(_Stream, _tagInfo))
                {
                    // and display what we get
                    this.textBoxAlbum.Text   = _tagInfo.album;
                    this.textBoxArtist.Text  = _tagInfo.artist;
                    this.textBoxTitle.Text   = _tagInfo.title;
                    this.textBoxComment.Text = _tagInfo.comment;
                    this.textBoxGenre.Text   = _tagInfo.genre;
                    this.textBoxYear.Text    = _tagInfo.year;
                }

                // play the stream
                if (_Stream != 0 && Bass.BASS_ChannelPlay(_Stream, false))
                {
                    //playing...
                    BASS_CHANNELINFO info = new BASS_CHANNELINFO();
                    if (Bass.BASS_ChannelGetInfo(_Stream, info))
                    {
                        // start the BPMCounter
                        _bpm.Reset(info.freq);
                        this.timerBPM.Start();

                        // display the channel info..
                        this.label1.Text = String.Format("Type={0}, Channels={1}, OrigRes={2}", Utils.BASSChannelTypeToString(info.ctype), info.chans, info.origres);
                    }
                }
                else
                {
                    MessageBox.Show(this, "Error: " + Enum.GetName(typeof(BASSError), Bass.BASS_ErrorGetCode()));
                }
            }
        }
Пример #23
0
 public void ReloadMusic()
 {
     if (Bass.BASS_ChannelIsActive(StreamHandle) != BASSActive.BASS_ACTIVE_STOPPED)
     {
         ResetPlayer();
     }
     if (FileName != null && System.IO.File.Exists(FileName))
     {
         StreamHandle = Bass.BASS_StreamCreateFile(FileName, 0, 0, BASSFlag.BASS_SAMPLE_FLOAT);
         Bass.BASS_ChannelPlay(StreamHandle, false);
         BASS_CHANNELINFO bassInfo = new BASS_CHANNELINFO();
         Bass.BASS_ChannelGetInfo(StreamHandle, bassInfo);
         CurrentBPM.Reset(bassInfo.freq);
         bpmTimer.Start();
     }
 }
Пример #24
0
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        private void Initialize()
        {
            _info = Bass.BASS_ChannelGetInfo(_handle);
            Log.Debug("Stream type: {0}", _info.ctype);

            if (_info.ctype != BASSChannelType.BASS_CTYPE_STREAM &&
                _info.ctype != BASSChannelType.BASS_CTYPE_STREAM_MIXER)
            {
                Log.Info("Stream info: {0}", _info.ToString());

                UpdateLocalFields();
                _streamContentType = GetStreamContentType();

                Log.Info("Stream content: {0}", _streamContentType);
            }
        }
Пример #25
0
        private void UpdateMatrix(int index)
        {
            double dhandle;

            this.FPinHandles[index].GetValue(0, out dhandle);

            ChannelInfo info = this.manager.GetChannel(Convert.ToInt32(dhandle));

            if (info != null)
            {
                int mixerhandle = 0;

                if (info.BassHandle.HasValue)
                {
                    mixerhandle = BassMix.BASS_Mixer_ChannelGetMixer(info.BassHandle.Value);
                }

                if (mixerhandle != 0)
                {
                    BASS_CHANNELINFO MIXER   = Bass.BASS_ChannelGetInfo(mixerhandle);
                    BASS_CHANNELINFO CHANNEL = Bass.BASS_ChannelGetInfo(info.BassHandle.Value);
                    float[,] matrix = new float[MIXER.chans, CHANNEL.chans];
                    BassMix.BASS_Mixer_ChannelGetMatrix(info.BassHandle.Value, matrix);
                    int idx = 0;



                    for (int i = 0; i < MIXER.chans; i++)
                    {
                        for (int j = 0; j < CHANNEL.chans; j++)
                        {
                            double level;
                            this.FPinLevels[index].GetValue(idx, out level);
                            matrix[i, j] = (float)level;

                            idx++;
                            if (idx == this.FPinLevels[index].SliceCount)
                            {
                                idx = 0;
                            }
                        }
                    }

                    BassMix.BASS_Mixer_ChannelSetMatrix(info.BassHandle.Value, matrix);
                }
            }
        }
Пример #26
0
 protected void setupChannelFromStream()
 {
     if (streamRef != 0)
     {
         info = new BASS_CHANNELINFO();
         Bass.BASS_ChannelGetInfo(streamRef, info);
         frequency = info.freq;
         this.mono = (info.chans == 1);
     }
     else
     {
         frequency = 44100;
         mono      = false;
     }
     setupEqualizer();
     updateGain();
 }
Пример #27
0
        /// <summary>
        /// Set the media type based on values from BASS.DLL
        /// </summary>
        /// <param name="psc">The IGenericSampleConfig onto which we set the mediatype</param>
        override public void SetMediaType(IGenericSampleConfig psc)
        {
            int lFrequency = 0;
            int lVolume    = 0;
            int lPan       = 0;

            WaveFormatEx     w     = new WaveFormatEx();
            BASS_CHANNELINFO lInfo = new BASS_CHANNELINFO();

            Bass.BASS_ChannelGetInfo(m_fChan, lInfo);
            if ((lInfo.flags & (int)BASSStream.BASS_SAMPLE_8BITS) == (int)BASSStream.BASS_SAMPLE_8BITS)
            {
                w.wBitsPerSample = 8;
            }
            else
            {
                w.wBitsPerSample = 16;
            }
            Bass.BASS_ChannelGetAttributes(m_fChan, ref lFrequency, ref lVolume, ref lPan);

            w.cbSize          = (short)Marshal.SizeOf(typeof(WaveFormatEx));
            w.nChannels       = (short)lInfo.chans;
            w.nSamplesPerSec  = lFrequency;
            w.wFormatTag      = 1;
            w.nAvgBytesPerSec = w.nSamplesPerSec * w.nBlockAlign;
            m_BytesPerSample  = (short)(w.nChannels * (w.wBitsPerSample / 8));
            m_Frequency       = lFrequency;
            m_Channels        = lInfo.chans;
            w.nBlockAlign     = (short)m_BytesPerSample;
            w.nAvgBytesPerSec = w.nSamplesPerSec * w.nBlockAlign;

            AMMediaType amt = new AMMediaType();

            amt.majorType  = MediaType.Audio;
            amt.subType    = MediaSubType.PCM;
            amt.formatType = FormatType.WaveEx;
            amt.formatPtr  = Marshal.AllocCoTaskMem(w.cbSize);
            amt.formatSize = w.cbSize;
            Marshal.StructureToPtr(w, amt.formatPtr, false);

            int hr = psc.SetMediaTypeEx(amt, BUFSIZE);

            DsError.ThrowExceptionForHR(hr);

            DsUtils.FreeAMMediaType(amt);
        }
Пример #28
0
        public async Task OpenFile(string fileName)
        {
            _openningStream = fileName;
            Stop();
            await Task.Run(() =>
            {
                if (ActiveStreamHandle != 0)
                {
                    ChannelPosition = 0;
                    Bass.BASS_StreamFree(ActiveStreamHandle);
                }

                if (File.Exists(fileName))
                {
                    ActiveStreamHandle = Bass.BASS_StreamCreateFile(fileName, 0, 0, openFileConfig);
                    if (ActiveStreamHandle != 0)
                    {
                        ChannelLength = Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle, Bass.BASS_ChannelGetLength(ActiveStreamHandle, 0));

                        //Obtain the sample rate of the sstream
                        var info = new BASS_CHANNELINFO();
                        Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                        sampleFrequency = info.freq;

                        // Set the stream to call Stop() when it ends.
                        int syncHandle = Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                                                                  BASSSync.BASS_SYNC_END,
                                                                  0,
                                                                  endTrackSyncProc,
                                                                  IntPtr.Zero);

                        if (syncHandle == 0)
                        {
                            throw new ArgumentException("Error establishing End Sync on file stream.", "path");
                        }

                        CanPlay = true;
                    }
                    else
                    {
                        Debug.WriteLine($"Failed to open file: {fileName},Error Code: {Bass.BASS_ErrorGetCode()}");
                    }
                }
            });
        }
Пример #29
0
        /// <summary>
        /// Create a Fingerprint and lookup the Recordings
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task <List <Recording> > GetRecordings(string file)
        {
            var stream = Bass.BASS_StreamCreateFile(file, 0, 0, BASSFlag.BASS_STREAM_DECODE);
            var chInfo = Bass.BASS_ChannelGetInfo(stream);

            var bufLen = (int)Bass.BASS_ChannelSeconds2Bytes(stream, 120.0);
            var buf    = new short[bufLen];

            var chromaContext = new ChromaContext();

            chromaContext.Start(chInfo.freq, chInfo.chans);

            var length = Bass.BASS_ChannelGetData(stream, buf, bufLen);

            chromaContext.Feed(buf, length / 2);

            chromaContext.Finish();

            var fingerPrint = chromaContext.GetFingerprint();

            Configuration.ClientKey = "mfbgmu2P";
            var lookupSvc = new LookupService();

            var len  = Bass.BASS_ChannelGetLength(stream, BASSMode.BASS_POS_BYTE);
            var time = Bass.BASS_ChannelBytes2Seconds(stream, len);

            Bass.BASS_StreamFree(stream);

            //var result = await lookupSvc.GetAsync(fingerPrint, Convert.ToInt32(time), new[] { "recordingids", "releases", "artists" });
            var trackIds = await lookupSvc.GetAsync(fingerPrint, Convert.ToInt32(time), new[] { "recordingids" });

            var recordings = new List <Recording>();

            foreach (var trackId in trackIds.Results)
            {
                foreach (var rec in trackId.Recordings)
                {
                    System.Threading.Thread.Sleep(400);
                    var recording = await Recording.GetAsync(rec.Id, new[] { "releases", "artists", "media", "discids" });

                    recordings.Add(recording);
                }
            }
            return(recordings);
        }
Пример #30
0
        public async Task OpenUrl(string url)
        {
            _openningStream = url;
            Stop();
            await Task.Run(() =>
            {
                int handle = Bass.BASS_StreamCreateURL(url, 0, openUrlConfig, null, IntPtr.Zero);
                if (handle != 0)
                {
                    if (_openningStream == url)
                    {
                        ActiveStreamHandle = handle;
                        ChannelLength      = Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle, Bass.BASS_ChannelGetLength(ActiveStreamHandle));
                        var info           = new BASS_CHANNELINFO();
                        Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                        sampleFrequency = info.freq;

                        int syncHandle = Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                                                                  BASSSync.BASS_SYNC_END,
                                                                  0,
                                                                  endTrackSyncProc,
                                                                  IntPtr.Zero);

                        if (syncHandle == 0)
                        {
                            throw new ArgumentException("Error establishing End Sync on file stream.", "url");
                        }

                        CanPlay = true;
                    }
                    else
                    {
                        if (!Un4seen.Bass.Bass.BASS_StreamFree(handle))
                        {
                            Debug.WriteLine("BASS_StreamFree() Failed:" + Un4seen.Bass.Bass.BASS_ErrorGetCode());
                        }
                    }
                }
                else
                {
                    Debug.WriteLine($"Failed to open URL: {url}, Error Code: {Bass.BASS_ErrorGetCode()}");
                }
            });
        }