Ejemplo n.º 1
0
 //запуск воспроизведения
 public static void Play(string filename, int vol)
 {
     if (Bass.BASS_ChannelIsActive(Stream) != BASSActive.BASS_ACTIVE_PAUSED)
     {
         //чтобы не начало одновременно играть два трека
         Stop();
         //с помощью метода InitBass(HZ) проверяем инициализацию библиотеки
         //если она инициализирована, загружаем трек
         //filename - какой трек будет воспроизводиться
         //0 - воспроизводится с начала
         //0 - длительность (до конца, т.е. оригинальный размер)
         if (InitBass(HZ))
         {
             Stream = Bass.BASS_StreamCreateFile(filename, 0, 0, BASSFlag.BASS_DEFAULT);
             //если файл открыт удачно, то Stream не равен нулю
             if (Stream != 0)
             {
                 //устанавливаем громкость трека
                 Volume = vol;
                 Bass.BASS_ChannelSetAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, Volume / 100F);
                 //запускаем воспроизведение
                 Bass.BASS_ChannelPlay(Stream, false);
             }
         }
     }
     else
     {
         Bass.BASS_ChannelPlay(Stream, false);
     }
     isStopped = false;
 }
Ejemplo n.º 2
0
        public void Play(float volume = 1)
        {
            int channel = Bass.BASS_SampleGetChannel(_sample, false);

            Bass.BASS_ChannelPlay(channel, false);
            Bass.BASS_ChannelSetAttribute(channel, BASSAttribute.BASS_ATTRIB_VOL, volume);
        }
Ejemplo n.º 3
0
        public override void Initialize()
        {
            Bass.BASS_ChannelPlay(_soundhandler, false);
            _texture = new Texture(window.Size.X, window.Size.Y);

            _rectangleShape         = new RectangleShape(new Vector2f(window.Size.X, window.Size.Y));
            _rectangleShape.Texture = _texture;

            _shader = new Shader(@"shaders\VertexShader.vert",
                                 @"shaders\Experiment2_MusicVisualization\lime2.frag");

            _shader.SetParameter("time1", 0);
            _shader.SetParameter("time2", 0);
            _shader.SetParameter("time3", 0);
            _shader.SetParameter("time4", 0);
            _shader.SetParameter("time5", 0);
            _shader.SetParameter("time6", 0);
            _shader.SetParameter("time7", 0);
            _shader.SetParameter("time8", 0);
            _shader.SetParameter("resolution", new Vector2f(window.Size.X, window.Size.Y));

            _rState         = new RenderStates(_shader);
            _rState.Texture = _texture;

            //_soundPlayer.Play();
        }
Ejemplo n.º 4
0
        private void buttonStreamCreate_Click(object sender, System.EventArgs e)
        {
            Bass.BASS_StreamFree(_stream);
            this.textBox1.Text = "";

            // test BASS_StreamCreate
            if (_fileName != String.Empty)
            {
                // open any file supported by BASS...
                _fs = File.OpenRead(_fileName);
                this.textBox1.Text += "Open file: " + _fs.Name + Environment.NewLine;

                // create the stream
                _stream             = Bass.BASS_StreamCreate(44100, 2, BASSFlag.BASS_DEFAULT, _myStreamCreate, IntPtr.Zero);
                this.textBox1.Text += "StreamCreateUser: "******"ChannelPlay: playing" + Environment.NewLine;
                }
                else
                {
                    this.textBox1.Text += String.Format("Error: {0}\n", Bass.BASS_ErrorGetCode());
                }
            }
        }
        void SE_Play()
        {
            //選択しているSEを再生
            if (IsClosing)
            {
                return;
            }
            Bass.BASS_ChannelStop(Stream);
            Bass.BASS_StreamFree(Stream);
            string SE_Count     = SE_Change_Window.Preset_List[SE_Change_Window.Preset_Index][SE_Lists.SelectedIndex + 1];
            int    StreamHandle = Bass.BASS_StreamCreateFile(SE_Count.Split('|')[SE_Play_Index - 1], 0, 0, BASSFlag.BASS_STREAM_DECODE);

            Stream = BassFx.BASS_FX_TempoCreate(StreamHandle, BASSFlag.BASS_FX_FREESOURCE);
            Bass.BASS_ChannelSetAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, 1f);
            Bass.BASS_ChannelSetDevice(Stream, Video_Mode.Sound_Device);
            Bass.BASS_ChannelPlay(Stream, true);
            if (SE_Play_Index < Select_SE_File_Count)
            {
                SE_Play_Index++;
                SE_Play_Number_T.Text = SE_Play_Index + "/" + Select_SE_File_Count;
            }
            else if (Select_SE_File_Count != 1 && SE_Play_Index == Select_SE_File_Count)
            {
                SE_Play_Index         = 1;
                SE_Play_Number_T.Text = SE_Play_Index + "/" + Select_SE_File_Count;
            }
        }
Ejemplo n.º 6
0
        void Play(String m_filename)
        {
            switch (Bass.BASS_ChannelIsActive(_stream))
            {
            case BASSActive.BASS_ACTIVE_STOPPED:
                Bass.BASS_StreamFree(_stream);
                if (!string.IsNullOrEmpty(m_filename))
                {
                    _fs     = System.IO.File.OpenRead(m_filename);
                    _stream = Bass.BASS_StreamCreateFileUser(BASSStreamSystem.STREAMFILE_NOBUFFER, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN | BASSFlag.BASS_STREAM_AUTOFREE, _myStreamCreateUser, IntPtr.Zero);
                    if (_stream != 0)
                    {
                        m_totaltime = String.Format(Utils.FixTimespan(Bass.BASS_ChannelBytes2Seconds(_stream, Bass.BASS_ChannelGetLength(_stream)), "MMSS"));
                        Bass.BASS_ChannelPlay(_stream, true);
                        MainProgressBar.Maximum = (int)Bass.BASS_ChannelBytes2Seconds(_stream, Bass.BASS_ChannelGetLength(_stream));
                        _maintimer.Start();
                        iconPlay.Kind = MaterialDesignThemes.Wpf.PackIconKind.Pause;
                        //
                    }
                }
                break;

            case BASSActive.BASS_ACTIVE_PLAYING:
                Bass.BASS_ChannelPause(_stream);
                iconPlay.Kind = MaterialDesignThemes.Wpf.PackIconKind.Play;
                break;

            case BASSActive.BASS_ACTIVE_PAUSED:
                Bass.BASS_ChannelPlay(_stream, false);
                iconPlay.Kind = MaterialDesignThemes.Wpf.PackIconKind.Pause;
                break;
            }
        }
Ejemplo n.º 7
0
        private void Simple_Load(object sender, System.EventArgs e)
        {
            // BassNet.Registration("your email", "your regkey");

            if (!Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, this.Handle))
            {
                MessageBox.Show(this, "Bass_Init error!");
                this.Close();
                return;
            }
            Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_BUFFER, 200);
            Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, 20);

            // already create a mixer
            _mixer = BassMix.BASS_Mixer_StreamCreate(44100, 2, BASSFlag.BASS_SAMPLE_FLOAT);
            if (_mixer == 0)
            {
                MessageBox.Show(this, "Could not create mixer!");
                Bass.BASS_Free();
                this.Close();
                return;
            }

            _mixerStallSync = new SYNCPROC(OnMixerStall);
            Bass.BASS_ChannelSetSync(_mixer, BASSSync.BASS_SYNC_STALL, 0L, _mixerStallSync, IntPtr.Zero);

            timerUpdate.Start();
            Bass.BASS_ChannelPlay(_mixer, false);
        }
Ejemplo n.º 8
0
 public bool Play(string fullPath)
 {
     if (State != ChannelStates.Ready)
     {
         throw new NotSupportedException($"ChannelState not valid! [ChannelState = {State.ToString()}]");
     }
     Stream = GetStream(fullPath);
     if (Stream != 0)
     {
         var playBackStartSyncProc  = new SYNCPROC(playBackStartCallback);
         var playBackEndSyncProc    = new SYNCPROC(playBackEndCallBack);
         var playBackPausedSyncProc = new SYNCPROC(playBackPausedCallBack);
         Bass.BASS_ChannelSetSync(Stream, BASSSync.BASS_SYNC_POS | BASSSync.BASS_SYNC_MIXTIME, 0, playBackStartSyncProc, IntPtr.Zero);
         Bass.BASS_ChannelSetSync(Stream, BASSSync.BASS_SYNC_END | BASSSync.BASS_SYNC_MIXTIME, 0, playBackEndSyncProc, IntPtr.Zero);
         Bass.BASS_ChannelSetSync(Stream, BASSSync.BASS_SYNC_STALL | BASSSync.BASS_SYNC_MIXTIME, 0, playBackPausedSyncProc, IntPtr.Zero);
         if (Bass.BASS_ChannelPlay(Stream, false))
         {
             State = ChannelStates.Playing;
         }
         return(true);
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 9
0
 private void playBackEndCallBack(int handle, int channel, int data, IntPtr user)
 {
     try
     {
         var eventType = BassEvent.PlaybackFinished;
         if (Repeat)
         {
             Seek(0);
             Bass.BASS_ChannelPlay(Stream, true);
             eventType = BassEvent.PlaybackRestarting;
             State     = ChannelStates.Playing;
         }
         else
         {
             cleanupStream();
         }
         if (this.BassActorEvent != null)
         {
             BassActorEvent(this, new BassEventArgs(eventType));
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Unhandled: {ex.Message}\nStackTrace: {ex.StackTrace}");
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        ///     Play stream
        /// </summary>
        public void Play()
        {
            //Check if the song is stopped
            if (Bass.BASS_ChannelIsActive(Handle) == BASSActive.BASS_ACTIVE_PAUSED)
            {
                if (Valid) //Check if the stream handle is valid
                {
                    if (Bass.BASS_ChannelPlay(Handle, false))
                    {
                        StreamStatus = StreamStatus.CanPause;
                    }
                }
            }
            else //song is stopped, load again
            {
                Open(); //Open the file since its stopped
                if (Bass.BASS_ChannelPlay(Handle, false))
                {
                    StreamStatus = StreamStatus.CanPause;
                }
            }
            if (Config.ReactorFade & !ReactorUsageLocked)
            {
                var fader = new Fader(this, FadeMode.Linear, 5, 250, false, Volume);

                fader.Start();
            }
            if (!Muted)
            {
                Bass.BASS_ChannelSetAttribute(Handle, BASSAttribute.BASS_ATTRIB_VOL, _volume);
            }
        }
Ejemplo n.º 11
0
        private void buttonStartRec_Click(object sender, System.EventArgs e)
        {
            this.buttonStartRec.Enabled = false;
            this.labelRec.Text          = "Recording...";

            // start recording paused
            _myRecProc = new RECORDPROC(MyRecoring);
            _recHandle = Bass.BASS_RecordStart(44100, 2, BASSFlag.BASS_RECORD_PAUSE, _myRecProc, new IntPtr(_encHandle));

            // needs 'lame.exe' !
            // the recorded data will be written to a file called rectest.mp3
            // create the encoder...192kbps, stereo
            // MP3 encoder setup
            lame                       = new EncoderLAME(_recHandle);
            lame.InputFile             = null;  //STDIN
            lame.OutputFile            = "rectest.mp3";
            lame.LAME_Bitrate          = (int)EncoderLAME.BITRATE.kbps_192;
            lame.LAME_Mode             = EncoderLAME.LAMEMode.Default;
            lame.LAME_TargetSampleRate = (int)EncoderLAME.SAMPLERATE.Hz_44100;
            lame.LAME_Quality          = EncoderLAME.LAMEQuality.Quality;

            monBuffer.Clear();
            checkBoxMonitor.Checked = false;

            // create a live recording WaveForm
            WF = new WaveForm();
            WF.FrameResolution = 0.01f;             // 10ms are nice
            // start a live recording waveform with 5sec. init size and 2sec. next size
            WF.RenderStartRecording(_recHandle, 5f, 2f);

            // really start recording
            lame.Start(null, IntPtr.Zero, false);
            Bass.BASS_ChannelPlay(_recHandle, false);
        }
Ejemplo n.º 12
0
        Single[] fft    = null; //массив данных спектра
        private void button1_Click(object sender, EventArgs e)
        {
            n = Bass.BASS_GetDevice();                             //получаем устройство по умолчанию
            if (Bass.BASS_Init(n, 44100, 0, IntPtr.Zero) == false) //попытка инициализации
            {
                MessageBox.Show("BASS_Init failed");
                return;
            }
            if (FileNAme != "") // Если подобрали свой файл
            {
                chan = Bass.BASS_StreamCreateFile(@FileNAme,
                                                  0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_SAMPLE_LOOP);//создаем поток в режиме FLOAT
            }
            else // Иначе откроем файл для визуализации по умолчанию.
            {
                chan = Bass.BASS_StreamCreateFile(@"C:\MP3\file.mp3",
                                                  0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_SAMPLE_LOOP);//создаем поток в режиме FLOAT
            }

            if (chan == 0)
            {
                MessageBox.Show("BASS_StreamCreateFile failed");
                return;
            }

            f = Bass.BASS_ChannelPlay(chan, false);//воспроизводим поток
            if (f == false)
            {
                MessageBox.Show("BASS_ChannelPlay failed");
                return;
            }
        }
Ejemplo n.º 13
0
        private void nextBtn_Click(object sender, EventArgs e)
        {
            if (Functions.PlaylistPosition < Functions.playlist.Count - 1)
            {
                if (Functions.playlist.Count > 1)
                {
                    Bass.BASS_ChannelStop(_stream);
                    var data = new string[6];
                    switch (Functions.PlayMode)
                    {
                    case 0:
                        data = Functions.NextTrack();
                        break;

                    case 1:
                        data = Functions.LoopTrack();
                        break;

                    case 2:
                        data = Functions.RandomTrack();
                        break;
                    }
                    SetPlayerData(data);
                    if (playerControl.playerControl.pause)
                    {
                        Bass.BASS_ChannelPlay(_stream, false); Discord.SetData(1);
                    }
                    // Set volume
                    float Volume = (float)volumeTrackBar.Value / 100;
                    Bass.BASS_ChannelSetAttribute(_stream, BASSAttribute.BASS_ATTRIB_VOL, Volume);
                    /////////////
                }
            }
        }
Ejemplo n.º 14
0
        public void Play(string fileName, int vol = 100)
        {
            if (_handle != 0)
            {
                Stop();
                _currentPosition = 0;
                OnTrackPositionProgressChanged(new TrackPositionProgrressChangedEventHandlerArgs()
                {
                    PositionSeconds = _currentPosition
                });
            }

            _handle = Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_DEFAULT);
            if (_handle != 0)
            {
                CurrentTrackLength = GetTrackLength();
                TAG_INFO tagInfo = BassTags.BASS_TAG_GetFromFile(fileName);
                OnTrackChanged(new TrackChangedEventHandlerArgs()
                {
                    TrackLength = CurrentTrackLength,
                    Title = tagInfo.title,
                    Album = tagInfo.album,
                    Artist = tagInfo.artist,
                    Image = tagInfo.PictureCount > 0 ? tagInfo.PictureGetImage(0): null,
                    Year = tagInfo.year
                });
                Bass.BASS_ChannelSetAttribute(_handle, BASSAttribute.BASS_ATTRIB_VOL, vol / 100f);
                Bass.BASS_ChannelPlay(_handle, false);
                _timer.Start();
            }
        }
 private void Toque()
 {
     if (dTmr.IsEnabled)
     {
         if (DateTime.Now - dtToque > TimeSpan.FromMilliseconds(400))
         {
             toques++;
             Bass.BASS_ChannelPlay(streamBeep, false);
             string strToques = toques > 1 ? string.Format("{0} toques", toques) : "1 toque";
             Dispatcher.Invoke(new Action(() =>
             {
                 if (dTmr.IsEnabled)
                 {
                     txtbToques.Text                 = strToques;
                     gridCen.Background              = new SolidColorBrush(Colors.Red);
                     txtbTempo.Foreground            = new SolidColorBrush(Colors.White);
                     txtbToques.Foreground           = txtbTempo.Foreground;
                     txtbSentidoDescricao.Foreground = txtbTempo.Foreground;
                     txtbSentido.Foreground          = txtbTempo.Foreground;
                     recImagemDisp.Fill              = txtbTempo.Foreground;
                 }
             }));
             dtToque = DateTime.Now;
         }
     }
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Воспроизведение треков
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="volume"></param>
 public static bool Play(string filename, int volume)
 {
     if (Bass.BASS_ChannelIsActive(Stream) != BASSActive.BASS_ACTIVE_PAUSED ||
         (Bass.BASS_ChannelIsActive(Stream) == BASSActive.BASS_ACTIVE_PAUSED && !filename.Equals(CurrentTrackName)))
     {
         Stop();
         if (InitAudio(HZ) && SetStream(filename))
         {
             Volume = volume;
             Bass.BASS_ChannelSetAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, Volume / 100f);
             Bass.BASS_ChannelPlay(Stream, false);
             CurrentTrackName = filename;
             InitEqualizer();
         }
         else
         {
             return(false);
         }
     }
     else
     {
         Bass.BASS_ChannelPlay(Stream, false);
     }
     isStoped = false;
     return(true);
 }
Ejemplo n.º 17
0
        public void playStream()
        {
            // set a sync to get the title updates out of the meta data...
            mySync = new SYNCPROC(MetaSync);
            Bass.BASS_ChannelSetSync(_Stream, BASSSync.BASS_SYNC_META, 0, mySync, IntPtr.Zero);
            Bass.BASS_ChannelSetSync(_Stream, BASSSync.BASS_SYNC_WMA_CHANGE, 0, mySync, IntPtr.Zero);

            //// start recording...
            //int rechandle = 0;
            //if (Bass.BASS_RecordInit(-1))
            //{
            //    _byteswritten = 0;
            //    myRecProc = new RECORDPROC(MyRecoring);
            //    rechandle = Bass.BASS_RecordStart(44100, 2, BASSFlag.BASS_RECORD_PAUSE, myRecProc, IntPtr.Zero);
            //}
            ////this.statusBar1.Text = "Playling...";

            // play the stream

            try
            {
                Bass.BASS_ChannelPlay(_Stream, false);
            }
            catch (Exception ex) { System.Windows.MessageBox.Show(ex.ToString()); }
            // record the stream
            //Bass.BASS_ChannelPlay(rechandle, false);
        }
Ejemplo n.º 18
0
        public void Play()
        {
            if (this.PlayPause == "Pause" || SelectedSong == null || chan == 0)
            {
                return;
            }

            if (dispatcherTimer != null)
            {
                dispatcherTimer.Stop();
            }

            Bass.BASS_ChannelPlay(chan, false);

            this.PlayPause = "Pause";

            if (dispatcherTimer == null)
            {
                dispatcherTimer          = new System.Windows.Threading.DispatcherTimer();
                dispatcherTimer.Tick    += new EventHandler(dispatcherTimer_Tick);
                dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            }

            dispatcherTimer.Start();
        }
Ejemplo n.º 19
0
        public override void Play()
        {
            if ((Bass.BASS_ChannelIsActive(_stream) != BASSActive.BASS_ACTIVE_PAUSED) || (Bass.BASS_ChannelIsActive(_stream) == BASSActive.BASS_ACTIVE_STOPPED))
            {
                Bass.BASS_StreamFree(_stream);

                _stream = Bass.BASS_StreamCreateFile(_source, 0, 0, BASSFlag.BASS_DEFAULT);
                //_stream = Bass.BASS_StreamCreateFile(_source, 0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
                if (_stream != 0)
                {
                    //костыли
                    Bass.BASS_ChannelGetAttribute(_stream, BASSAttribute.BASS_ATTRIB_VOL, ref vol);
                    //костыли
                    Volume = vol * 100F;
                    //костыли
                    Bass.BASS_ChannelSetAttribute(_stream, BASSAttribute.BASS_ATTRIB_VOL, (float)_volume);
                    Bass.BASS_ChannelPlay(_stream, false); //2й параметр это луп (рестарт)
                    //   MessageBox.Show(vol.ToString());
                }
                else
                {
                    MessageBox.Show("Error= " + Bass.BASS_ErrorGetCode().ToString());
                }
            }
            else
            {
                Bass.BASS_ChannelPlay(_stream, false);
            }

            //       MessageBox.Show(Duration.ToString());
//
            // Position = TimeSpan.Parse("00:01:00");// 40000;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Play the MP3 song stored in the buffer lameEncodedBytes
        /// </summary>
        /// <param name="buffer"></param>
        private void PlayByteBlog(byte[] buffer)
        {
            if (_blogStreamHandle == 0 || Bass.BASS_ChannelIsActive(_blogStreamHandle) != BASSActive.BASS_ACTIVE_PLAYING)
            {
                // create a handle to the buffer and pin it, so that the Garbage Collector will not remove it
                GCHandle hGC = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                // create the stream (AddrOfPinnedObject delivers the necessary IntPtr)
                _blogStreamHandle = Bass.BASS_StreamCreateFile(hGC.AddrOfPinnedObject(), 0, buffer.Length, BASSFlag.BASS_DEFAULT);

                //...let it play...

                if (buffer != null && buffer.Length > 0)
                {
                    if (_blogStreamHandle != 0 && Bass.BASS_ChannelPlay(_blogStreamHandle, false))
                    {
                        Msg("Lame MP3 playback started");
                        Msg("MP3 has " + lameEncodedBytes.Length + " bytes");
                    }
                    else
                    {
                        BASSError error = Bass.BASS_ErrorGetCode();
                        Msg(Enum.GetName(typeof(BASSError), error));
                    }
                }
                hGC.Free();
            }
            else
            {
                Msg("Mp3 data is still playing");
            }
        }
Ejemplo n.º 21
0
        private void buttonStreamCreateUser_Click(object sender, System.EventArgs e)
        {
            Bass.BASS_StreamFree(_stream);
            this.textBox1.Text = "";

            // test BASS_StreamCreateUser
            if (_fileName != String.Empty)
            {
                // open the file...
                _fs = File.OpenRead(_fileName);
                this.textBox1.Text += "Open file: " + _fs.Name + Environment.NewLine;

                // create the stream
                // Note: The BASS_STREAM_PRESCAN flag is only used to demo what is happening when set.
                //       As it generates a lot of output at the beginning you might remove it.
                _stream             = Bass.BASS_StreamCreateFileUser(BASSStreamSystem.STREAMFILE_NOBUFFER, BASSFlag.BASS_STREAM_PRESCAN | BASSFlag.BASS_STREAM_AUTOFREE, _myStreamCreateUser, IntPtr.Zero);
                this.textBox1.Text += "StreamCreate: " + _stream.ToString() + Environment.NewLine;
                // play the stream
                if (_stream != 0 && Bass.BASS_ChannelPlay(_stream, false))
                {
                    this.textBox1.Text += "ChannelPlay: playing" + Environment.NewLine;
                }
                else
                {
                    this.textBox1.Text += String.Format("Error: {0}\n", Bass.BASS_ErrorGetCode());
                }
            }
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            // init BASS using the default output device
            if (Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero))
            {
                // create a stream channel from a file
                int stream = Bass.BASS_StreamCreateFile("test.mp3", 0L, 0L, BASSFlag.BASS_DEFAULT);
                if (stream != 0)
                {
                    // play the channel
                    Bass.BASS_ChannelPlay(stream, false);
                }
                else
                {
                    // error
                    Console.WriteLine("Stream error: {0}", Bass.BASS_ErrorGetCode());
                }

                // wait for a key
                Console.WriteLine("Press any key to exit");
                Console.ReadKey(false);

                // free the stream
                Bass.BASS_StreamFree(stream);
                // free BASS
                Bass.BASS_Free();
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Play a pre-loaded sound
 /// </summary>
 /// <param name="sound"></param>
 public void PlaySound(UISound sound)
 {
     if (sound != null)
     {
         Bass.BASS_ChannelPlay(sound.ThisChannel, false);
     }
 }
        /// <summary>
        ///		This function makes sure your default device is being used, if not, reload Bass and the song back and continue as if nothing happened.
        /// </summary>
        private void CheckDevice()
        {
            if (!BassManager.CheckDevice(streamID))
            {
                var pos  = Bass.BASS_ChannelGetPosition(streamID, BASSMode.BASS_POS_BYTES);
                var secs = TimeSpan.FromSeconds(Bass.BASS_ChannelBytes2Seconds(streamID, pos));

                var state  = Bass.BASS_ChannelIsActive(streamID);
                var volume = 0.3f;

                Bass.BASS_ChannelGetAttribute(streamID, BASSAttribute.BASS_ATTRIB_VOL, ref volume);

                BassManager.Reload();

                Load(lastFile);

                Volume      = volume;
                CurrentTime = secs;

                switch (state)
                {
                case BASSActive.BASS_ACTIVE_PAUSED:
                case BASSActive.BASS_ACTIVE_STOPPED:
                    Bass.BASS_ChannelPause(streamID);
                    Bass.BASS_ChannelSetPosition(streamID, pos, BASSMode.BASS_POS_BYTES);
                    break;

                case BASSActive.BASS_ACTIVE_STALLED:
                case BASSActive.BASS_ACTIVE_PLAYING:
                    Bass.BASS_ChannelPlay(streamID, false);
                    break;
                }
            }
        }
Ejemplo n.º 25
0
        public void CheckForEndAndReplay()
        {
            if (!IsReversed)
            {
                if (AudioStream.Position >= AudioStream.Length && Loop)
                {
                    Bass.BASS_ChannelPlay(AudioStream.StreamHandle, false);
                }

                if (IsPlayingBetweenMarks && (AudioStream.Position >= MarkB || AudioStream.Position < MarkA))
                {
                    AudioStream.Position = MarkA;
                }
            }
            else
            {
                if (AudioStream.Position <= 0 && Loop)
                {
                    AudioStream.Position = AudioStream.Length;
                    Bass.BASS_ChannelPlay(AudioStream.StreamHandle, false);
                }

                if (IsPlayingBetweenMarks && (AudioStream.Position <= MarkA || AudioStream.Position > MarkB))
                {
                    AudioStream.Position = MarkB;
                }
            }
        }
Ejemplo n.º 26
0
        public void StartMusic(string title)
        {
            UnityEngine.Debug.Log("Start " + title);

            if (!_IsEnabled)
            {
                return;
            }

            UnityEngine.Debug.Log("Engine is started");

            if (_CurrentStream != 0)
            {
                Bass.BASS_ChannelStop(_CurrentStream);
                _CurrentStream = 0;
            }

            int stream = Bass.BASS_StreamCreateFile(title, 0, 0, BASSFlag.BASS_SAMPLE_FLOAT);

            if (stream != 0)
            {
                UnityEngine.Debug.Log("Start streaming");
                Bass.BASS_ChannelPlay(stream, false);
                _CurrentStream = stream;
                long len = Bass.BASS_ChannelGetLength(_CurrentStream, BASSMode.BASS_POS_BYTES);
                _CurrentStreamTime = Bass.BASS_ChannelBytes2Seconds(_CurrentStream, len);
                _CurrentTime       = 0.0d;
            }
            else
            {
                UnityEngine.Debug.Log("Cannot start music " + Bass.BASS_ErrorGetCode());
                Bass.BASS_ChannelStop(_CurrentStream);
                _CurrentStream = 0;
            }
        }
Ejemplo n.º 27
0
        public void PlaySound(string file, int volume)
        {
            Log.InfoFormat("Playing sound '{0}' at volume '{1}'", file, volume);
            if (string.IsNullOrEmpty(file))
            {
                return;
            }

            try
            {
                // create a stream channel from a file
                int stream = Bass.BASS_StreamCreateFile(file, 0L, 0L, BASSFlag.BASS_DEFAULT | BASSFlag.BASS_STREAM_AUTOFREE);
                if (stream != 0)
                {
                    Bass.BASS_ChannelSetAttribute(stream, BASSAttribute.BASS_ATTRIB_VOL, (volume / 100f));
                    Bass.BASS_ChannelPlay(stream, false);
                }
                else
                {
                    throw new ApplicationException(string.Format(Resources.BASS_UNABLE_TO_CREATE_STREAM_FROM_FILE, file));
                }
            }
            catch (Exception exception)
            {
                //Don't publish error - the error handler tries to play a sound file which could loop us right back here
                Log.Error("Exception encountered within the AudioService", exception);
            }
        }
Ejemplo n.º 28
0
        private Bitmap DrawSpectrogram(string fileName, int height, int stepsPerSecond, IntPtr Handle)
        {
            Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, Handle);
            int channel = Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_DEFAULT);

            long   len  = Bass.BASS_ChannelGetLength(channel, BASSMode.BASS_POS_BYTES); // the length in bytes
            double time = Bass.BASS_ChannelBytes2Seconds(channel, len);                 // the length in seconds

            int steps = (int)Math.Floor(stepsPerSecond * time);

            Bitmap   result = new Bitmap(steps, height);
            Graphics g      = Graphics.FromImage(result);

            Visuals visuals = new Visuals();

            Bass.BASS_ChannelPlay(channel, false);

            for (int i = 0; i < steps; i++)
            {
                Bass.BASS_ChannelSetPosition(channel, 1.0 * i / stepsPerSecond);
                visuals.CreateSpectrum3DVoicePrint(channel, g, new Rectangle(0, 0, result.Width, result.Height), Color.Black, Color.White, i, true, true);
            }

            Bass.BASS_ChannelStop(channel);

            Bass.BASS_Stop();
            Bass.BASS_Free();

            return(result);
        }
    public override bool Play(float playPoint = 0, bool restart = false)
    {
        base.Play(playPoint, restart);

        int channel = Bass.BASS_SampleGetChannel(audioHandle, false);

        bool isPlaying = Bass.BASS_ChannelIsActive(channel) != BASSActive.BASS_ACTIVE_STOPPED && Bass.BASS_ChannelIsActive(channel) != BASSActive.BASS_ACTIVE_PAUSED;

        if (onlyPlayIfStopped && isPlaying)
        {
            return(false);
        }

        if (channel != 0)
        {
            Bass.BASS_ChannelSetAttribute(channel, BASSAttribute.BASS_ATTRIB_VOL, volume);
            Bass.BASS_ChannelSetAttribute(channel, BASSAttribute.BASS_ATTRIB_PAN, pan);

            Bass.BASS_ChannelPlay(channel, restart);
            return(true);
        }
        else
        {
            UnityEngine.Debug.LogError("Error when playing sample stream: " + Bass.BASS_ErrorGetCode() + ", " + audioHandle);
        }

        return(false);
    }
Ejemplo n.º 30
0
        public static async void startBassStream(string files, int vol)
        {
            await Task.Run(() =>
            {
                Bass.BASS_StreamFree(audioStreamBass);

                if (InitBass(HZ))
                {
                    Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_ASYNCFILE_BUFFER, 5000);
                    Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, 5000);
                    audioStreamBass = Bass.BASS_StreamCreateURL(files, 0, BASSFlag.BASS_STREAM_AUTOFREE | BASSFlag.BASS_STREAM_STATUS, null, IntPtr.Zero);
                    BassTag.syncStreamTitleUpdates(audioStreamBass);
                }
                if (audioStreamBass != 0 && Bass.BASS_ChannelPlay(audioStreamBass, true))
                {
                    Volume = vol;
                    Bass.BASS_ChannelSetAttribute(audioStreamBass, BASSAttribute.BASS_ATTRIB_VOL, Volume / 100.0F);
                    BassTag.updateTags();
                }
                else
                {
                    MessageBox.Show("Радиостанция в данный момент недоступна.\nПроверьте интернет-соединение.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            });
        }