Esempio n. 1
0
        public DirectXOutputDevice(Controller controller)
            : base(controller)
        {
            _streamWriteProcDelegate = OutputStreamWriteProc;
            _deviceNo = GetDeviceNo();

            // TODO: move to SetStream?
            BASSInit flags = BASSInit.BASS_DEVICE_DEFAULT;

            // Because all deviceinfo is saved in a static dictionary,
            // we need to determine the latency only once.
            if (!_deviceInfos.ContainsKey(_deviceNo))
            {
                flags |= BASSInit.BASS_DEVICE_LATENCY;
            }

            bool result = Bass.BASS_Init(
                _deviceNo,
                44100, //Only relevant for -> pre-XP (VxD drivers)
                flags,
                IntPtr.Zero);

            BASSError?bassInitErrorCode = result ? null : new BASSError?(Bass.BASS_ErrorGetCode());

            // If the GetDeviceNo() method returned BassConstants.BassDefaultDevice, we must request the actual device number
            // of the choosen default device
            _deviceNo = Bass.BASS_GetDevice();

            if (bassInitErrorCode.HasValue)
            {
                if (bassInitErrorCode.Value == BASSError.BASS_ERROR_ALREADY)
                {
                    if (!Bass.BASS_SetDevice(_deviceNo))
                    {
                        throw new BassLibraryException("BASS_SetDevice");
                    }
                    bassInitErrorCode = null;
                }
            }

            if (bassInitErrorCode.HasValue)
            {
                throw new BassLibraryException("BASS_Init", bassInitErrorCode.Value);
            }

            CollectDeviceInfo(_deviceNo);

            int ms = Convert.ToInt32(Controller.GetSettings().DirectSoundBufferSizeMilliSecs);

            if (!Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_BUFFER, ms))
            {
                throw new BassLibraryException("BASS_SetConfig");
            }

            // Enable update thread while the output device is active
            if (!Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, ms / 4))
            {
                throw new BassLibraryException("BASS_SetConfig");
            }
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            this._streamProc = null;
            this._buffer     = null;
        }
Esempio n. 3
0
        public int EnqueueSamples(int channels, int rate, byte[] samples, int frames)
        {
            int consumed = 0;
            if (_basbuffer == null)
            {
                Bass.BASS_Init(-1, rate, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);
                _basbuffer = new BASSBuffer(0.5f, rate, channels, 2);
                _streamproc = new STREAMPROC(Reader);

                if (_lazyVolumeSet)
                {
                    Volume = _lazyVolumeValue;
                }

                Bass.BASS_ChannelPlay(
                    Bass.BASS_StreamCreate(rate, channels, BASSFlag.BASS_DEFAULT, _streamproc, IntPtr.Zero),
                    false
                    );
            }

            if (_basbuffer.Space(0) > samples.Length)
            {
                _basbuffer.Write(samples, samples.Length);
                consumed = frames;
            }

            return consumed;
        }
Esempio n. 4
0
        public override void Initialize(int deviceid)
        {
            Bass.BASS_SetDevice(deviceid);

            _myStreamCreate = new STREAMPROC(MyFileProc);

            int handle = Bass.BASS_StreamCreate(44100, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT, _myStreamCreate, IntPtr.Zero);

            BASSFlag flag = BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_FX_FREESOURCE;

            if (this.IsDecoding)
            {
                flag = flag | BASSFlag.BASS_STREAM_DECODE;
            }

            if (this.Mono)
            {
                flag = flag | BASSFlag.BASS_SAMPLE_MONO;
            }

            handle = BassFx.BASS_FX_TempoCreate(handle, flag);

            this.BassHandle = handle;

            this.OnInitialize();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            Un4seen.Bass.BassNet.Registration("*****@*****.**", "2X113281839322");
            Un4seen.Bass.BassNet.OmitCheckVersion = true;
            bool bassinit = Un4seen.Bass.Bass.BASS_Init(0, sampleRate, Un4seen.Bass.BASSInit.BASS_DEVICE_DEFAULT, System.IntPtr.Zero);

            if (bassinit)
            {
                streamCreate = new STREAMPROC(WaveformProc);
                channel      = Bass.BASS_StreamCreate(sampleRate, 2, BASSFlag.BASS_DEFAULT, streamCreate, IntPtr.Zero);
                if (channel != 0)
                {
                    bufferLength = Bass.BASS_ChannelSeconds2Bytes(channel, (double)Bass.BASS_GetConfig(BASSConfig.BASS_CONFIG_BUFFER) / 1000d);
                    data         = new short[bufferLength];

                    playSine();
                }
                else
                {
                    Un4seen.Bass.BASSError error = Un4seen.Bass.Bass.BASS_ErrorGetCode();
                    Console.WriteLine(error.ToString());
                }
            }
            else
            {
                Console.WriteLine("FAIL");
            }

            Console.ReadLine();
        }
Esempio n. 6
0
 public DSP_BufferStream()
 {
     _configBuffer      = 500;
     _isOutputBuffered  = true;
     _bufferStreamFlags = BASSFlag.BASS_MUSIC_DECODE;
     ConfigBuffer       = Bass.BASS_GetConfig(BASSConfig.BASS_CONFIG_BUFFER);
     _streamProc        = new STREAMPROC(BassStreamProc);
 }
Esempio n. 7
0
 public DSP_BufferStream()
 {
     _configBuffer = 500;
     _isOutputBuffered = true;
     _bufferStreamFlags = BASSFlag.BASS_MUSIC_DECODE;
     ConfigBuffer = Bass.BASS_GetConfig(BASSConfig.BASS_CONFIG_BUFFER);
     _streamProc = new STREAMPROC(BassStreamProc);
 }
Esempio n. 8
0
 public DSP_BufferStream(int channel, int priority) : base(channel, priority, IntPtr.Zero)
 {
     _configBuffer      = 500;
     _isOutputBuffered  = true;
     _bufferStreamFlags = BASSFlag.BASS_MUSIC_DECODE;
     ConfigBuffer       = Bass.BASS_GetConfig(BASSConfig.BASS_CONFIG_BUFFER);
     _streamProc        = new STREAMPROC(BassStreamProc);
 }
Esempio n. 9
0
 public DSP_BufferStream(int channel, int priority)
     : base(channel, priority, IntPtr.Zero)
 {
     _configBuffer = 500;
     _isOutputBuffered = true;
     _bufferStreamFlags = BASSFlag.BASS_MUSIC_DECODE;
     ConfigBuffer = Bass.BASS_GetConfig(BASSConfig.BASS_CONFIG_BUFFER);
     _streamProc = new STREAMPROC(BassStreamProc);
 }
Esempio n. 10
0
 public UserSampleStream(uint freq, uint channels, StreamProc proc, StreamFlag flag, int getData_retryMax = 0)
     : base(getData_retryMax)
 {
     this.streamProc = (handle, buffer, length, user) => this.disposed ? 0x80000000 : this.proc(buffer, length);
     this.proc       = proc;
     this.handle     = _BASS_StreamCreate(freq, channels, (uint)flag, this.streamProc, (IntPtr)this.GetHashCode());
     if (this.handle == IntPtr.Zero)
     {
         throw new BASSException("UserSampleStream: BASS_StreamCreate Failed.");
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Creates a user sample stream.
        /// </summary>
        /// <param name="freq">The default sample rate. The sample rate can be changed using BASS_ChannelSetAttribute. </param>
        /// <param name="chans">The number of channels... 1 = mono, 2 = stereo, 4 = quadraphonic, 6 = 5.1, 8 = 7.1. </param>
        /// <param name="flags">A combination of these flags.</param>
        /// <param name="proc">The user defined stream writing function, or one of the following.
        /// STREAMPROC_DEVICE Create a "dummy" stream for the device's final output mix. This allows DSP/FX to be applied to all channels that are playing on the device,
        /// rather than individual channels. DSP/FX parameter change latency is also reduced because channel playback buffering is avoided. The stream is created with the device's current output sample format;
        /// the freq, chans, and flags parameters are ignored.It will always be floating-point except on platforms/architectures that do not support floating-point (see BASS_CONFIG_FLOAT), where it will be 16-bit instead.
        /// STREAMPROC_DUMMY Create a "dummy" stream. A dummy stream does not have any sample data of its own, but a decoding dummy stream (with BASS_STREAM_DECODE flag) can be used to apply DSP/FX processing to any sample data, by setting DSP/FX on the stream and feeding the data through BASS_ChannelGetData. The dummy stream should have the same sample format as the data being fed through it.
        /// STREAMPROC_PUSH Create a "push" stream.Instead of BASS pulling data from a STREAMPROC function, data is pushed to BASS via BASS_StreamPutData.</param>
        /// <param name="user">User instance data to pass to the callback function. Unused when creating a dummy or push stream. </param>
        /// <returns>If successful, the new stream's handle is returned, else throw WavException</returns>
        public static int StreamCreate(int freq, int chans, BASSFlag flags, STREAMPROC proc, IntPtr user)
        {
            int handle = NativeMethods.BASS_StreamCreate(freq, chans, flags, proc, IntPtr.Zero);

            if (handle == 0)
            {
                throw new WavException(BassErrorCode.GetErrorInfo());
            }

            return(handle);
        }
    public DirectXOutputDevice(Controller controller)
    {
      _controller = controller;
      _deviceState = DeviceState.Stopped;
      _streamWriteProcDelegate = OutputStreamWriteProc;
      _silence = new Silence();

      _deviceNo = GetDeviceNo();

      BASSInit flags = BASSInit.BASS_DEVICE_DEFAULT;

      // Because all deviceinfo is saved in a static dictionary,
      // we need to determine the latency only once.
      if (!_deviceInfos.ContainsKey(_deviceNo))
        flags |= BASSInit.BASS_DEVICE_LATENCY;

      bool result = Bass.BASS_Init(
          _deviceNo,
          44100, //Only relevant for -> pre-XP (VxD drivers)
          flags,
          IntPtr.Zero);

      BASSError? bassInitErrorCode = result ? null : new BASSError?(Bass.BASS_ErrorGetCode());

      // If the GetDeviceNo() method returned BassConstants.BassDefaultDevice, we must request the actual device number
      // of the choosen default device
      _deviceNo = Bass.BASS_GetDevice();

      if (bassInitErrorCode.HasValue)
      {
        if (bassInitErrorCode.Value == BASSError.BASS_ERROR_ALREADY)
        {
          if (!Bass.BASS_SetDevice(_deviceNo))
            throw new BassLibraryException("BASS_SetDevice");
          bassInitErrorCode = null;
        }
      }

      if (bassInitErrorCode.HasValue)
        throw new BassLibraryException("BASS_Init", bassInitErrorCode.Value);

      CollectDeviceInfo(_deviceNo);

      int ms = Convert.ToInt32(Controller.GetSettings().DirectSoundBufferSize.TotalMilliseconds);

      if (!Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_BUFFER, ms))
        throw new BassLibraryException("BASS_SetConfig");

      // Enable update thread while the output device is active
      if (!Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, ms / 4))
        throw new BassLibraryException("BASS_SetConfig");
    }
Esempio n. 13
0
 private void checkBoxMonitor_CheckedChanged(object sender, System.EventArgs e)
 {
     if (checkBoxMonitor.Checked)
     {
         monProc   = new STREAMPROC(MonitoringStream);
         monStream = Bass.BASS_StreamCreate(44100, 2, 0, monProc, IntPtr.Zero); // user = reader#
         Bass.BASS_ChannelPlay(monStream, false);
     }
     else
     {
         Bass.BASS_StreamFree(monStream);
     }
 }
Esempio n. 14
0
        public PlaybackBuffer(Controller controller)
        {
            _controller = controller;
            _silence    = new Silence();

            _bufferSize = TimeSpan.FromMilliseconds(Controller.GetSettings().PlaybackBufferSizeMilliSecs);

            _streamWriteProcDelegate       = OutputStreamWriteProc;
            _vizRawStreamWriteProcDelegate = VizRawStreamWriteProc;

            _notifyBufferUpdateThread = new AutoResetEvent(false);
            _updateThreadFinished     = new AutoResetEvent(false);
        }
Esempio n. 15
0
 private PlaybackSession(Controller controller, int channels, int sampleRate, bool isPassThrough)
 {
     _controller              = controller;
     _playbackProcessor       = _controller.PlaybackProcessor;
     _playbackBuffer          = new PlaybackBuffer(controller);
     _upDownMixer             = new UpDownMixer();
     _vstProcessor            = new VSTProcessor();
     _winAmpDSPProcessor      = new WinAmpDSPProcessor(controller);
     _channels                = channels;
     _sampleRate              = sampleRate;
     _isPassThrough           = isPassThrough;
     _streamWriteProcDelegate = OutputStreamWriteProc;
     _state = SessionState.Reset;
 }
Esempio n. 16
0
    public PlaybackBuffer(Controller controller)
    {
      _controller = controller;
      _silence = new Silence();

      BassPlayerSettings settings = Controller.GetSettings();

      _bufferSize = settings.PlaybackBufferSize;

      _streamWriteProcDelegate = OutputStreamWriteProc;
      _vizRawStreamWriteProcDelegate = VizRawStreamWriteProc;

      _notifyBufferUpdateThread = new AutoResetEvent(false);
      _updateThreadFinished = new AutoResetEvent(false);
    }
Esempio n. 17
0
        public PlaybackBuffer(Controller controller)
        {
            _controller = controller;
            _silence    = new Silence();

            BassPlayerSettings settings = Controller.GetSettings();

            _bufferSize = settings.PlaybackBufferSize;

            _streamWriteProcDelegate       = OutputStreamWriteProc;
            _vizRawStreamWriteProcDelegate = VizRawStreamWriteProc;

            _notifyBufferUpdateThread = new AutoResetEvent(false);
            _updateThreadFinished     = new AutoResetEvent(false);
        }
Esempio n. 18
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="waveInfo">音频信息</param>
        /// <param name="bufferCapcity">缓存容量,小于等于0自动计算</param>
        public StreamSoundPlayer(WaveInfo waveInfo, int bufferCapcity = -1)
            : base(SoundPlayerType.Stream)
        {
            this._waveInfo = waveInfo;
            int bitByteCount;


            BASSFlag flags;

            switch (waveInfo.SampleBit)
            {
            case SampleType.Sample8Bit:
                flags        = BASSFlag.BASS_DEFAULT | BASSFlag.BASS_SAMPLE_8BITS;
                bitByteCount = 1;
                break;

            case SampleType.Sample16Bit:
                flags        = BASSFlag.BASS_DEFAULT;
                bitByteCount = 2;
                break;

            case SampleType.Sample32Bit:
                flags        = BASSFlag.BASS_DEFAULT | BASSFlag.BASS_SAMPLE_FLOAT;
                bitByteCount = 4;
                break;

            default:
                throw new NotImplementedException($"未实现的采样类型:{waveInfo.SampleBit.ToString()}");
            }

            if (bufferCapcity == -1)
            {
                bufferCapcity = waveInfo.SampleRate * waveInfo.ChannelCount * bitByteCount * 10;//默认缓存10秒数据
            }

            if (bufferCapcity > 0)
            {
                this._buffer = new byte[bufferCapcity];
            }

            this._streamProc = new STREAMPROC(this.StreamProcCallback);
            base._handle     = WavHelper.StreamCreate(waveInfo.SampleRate, waveInfo.ChannelCount, flags, this._streamProc, IntPtr.Zero);
            //base._device = WavHelper.ChannelGetDevice(base._handle);
        }
Esempio n. 19
0
        public int EnqueueSamples(int channels, int rate, byte[] samples, int frames)
        {
            int consumed = 0;
            if (basbuffer == null)
            {
                Bass.BASS_Init(-1, rate, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);
                basbuffer = new BASSBuffer(0.5f, rate, channels, 2);
                streamproc = Reader;
                currentHandle = Bass.BASS_StreamCreate(rate, channels, BASSFlag.BASS_DEFAULT, streamproc, IntPtr.Zero);
                Bass.BASS_ChannelPlay(currentHandle, false);
            }

            if (basbuffer.Space(0) > samples.Length)
            {
                basbuffer.Write(samples, samples.Length);
                consumed = frames;
            }

            return consumed;
        }
Esempio n. 20
0
        private void CreateFileUser_Load(object sender, System.EventArgs e)
        {
            //BassNet.Registration("your email", "your regkey");

            if (Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, this.Handle))
            {
                // all fine
                // we alraedy create the user callback methods...
                _myStreamCreate = new STREAMPROC(MyFileProc);

                _myStreamCreateUser = new BASS_FILEPROCS(
                    new FILECLOSEPROC(MyFileProcUserClose),
                    new FILELENPROC(MyFileProcUserLength),
                    new FILEREADPROC(MyFileProcUserRead),
                    new FILESEEKPROC(MyFileProcUserSeek));
            }
            else
            {
                MessageBox.Show(this, "Bass_Init error!");
            }
        }
Esempio n. 21
0
        public int EnqueueSamples(int channels, int rate, byte[] samples, int frames)
        {
            int consumed = 0;

            if (basbuffer == null)
            {
                Bass.BASS_Init(-1, rate, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);
                basbuffer     = new BASSBuffer(0.5f, rate, channels, 2);
                streamproc    = Reader;
                currentHandle = Bass.BASS_StreamCreate(rate, channels, BASSFlag.BASS_DEFAULT, streamproc, IntPtr.Zero);
                Bass.BASS_ChannelPlay(currentHandle, false);
            }

            if (basbuffer.Space(0) > samples.Length)
            {
                basbuffer.Write(samples, samples.Length);
                consumed = frames;
            }

            return(consumed);
        }
Esempio n. 22
0
        private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            System.IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;

            BassNet.Registration("*****@*****.**", "2X3931422312422");
            if (Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, hwnd))
            {
                _myStreamCreate = new STREAMPROC(MyFileProc);

                _myStreamCreateUser = new BASS_FILEPROCS(
                    new FILECLOSEPROC(MyFileProcUserClose),
                    new FILELENPROC(MyFileProcUserLength),
                    new FILEREADPROC(MyFileProcUserRead),
                    new FILESEEKPROC(MyFileProcUserSeek));
                MainVolume.Value = Bass.BASS_GetVolume() * 100;
                if (Bass.BASS_GetVolume() >= 80)
                {
                    packicon_volumestate.Kind = MaterialDesignThemes.Wpf.PackIconKind.VolumeHigh;
                }
                _maintimer = new System.Windows.Threading.DispatcherTimer()
                {
                    Interval = TimeSpan.FromMilliseconds(500)
                };
                _maintimer.Tick += new EventHandler(update_elapsedtime);

                _lyrictimer = new System.Windows.Threading.DispatcherTimer()
                {
                    Interval = TimeSpan.FromMilliseconds(500)
                };
                _lyrictimer.Tick += new EventHandler(_lyrictimer_Tick);

                lyricShow = new LyricShow(CanvasLyric, StackPanelCommonLyric, CanvasFocusLyric, TBFocusLyricBack, CanvasFocusLyricFore, TBFocusLyricFore);
                getLT     = new GetLyricAndLyricTime();
            }
            else
            {
                System.Windows.MessageBox.Show(this, "Bass_Init error!");
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Start PCM play
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnPlayPcm_Click(object sender, EventArgs e)
 {
     if (pcmImportStreamHandle == 0 || Bass.BASS_ChannelIsActive(pcmImportStreamHandle) != BASSActive.BASS_ACTIVE_PLAYING)
     {
         Msg("Raw PCM playback started");
         Msg("Raw PCM has " + pcmMemStrm.Length + " bytes");
         pcmMemStrm.Seek(0, SeekOrigin.Begin);
         playPcmProc           = new STREAMPROC(ImportPcmCallBack);
         pcmImportStreamHandle = Bass.BASS_StreamCreate(44100, 2, 0, playPcmProc, IntPtr.Zero); // user = reader#
         Bass.BASS_ChannelPlay(pcmImportStreamHandle, false);
         btnRecord.Enabled     = true;
         btnStopRecord.Enabled = false;
         btnPlayPcm.Enabled    = true;
         btnStopPcm.Enabled    = true;
         btnPlayLame.Enabled   = true;
         timer1.Enabled        = true;
         //btnStopLame.Enabled = true;
     }
     else
     {
         Msg("Raw PCM is still playing!");
     }
 }
        private async Task <bool> Init(string configPath, string agentsPath, string commandsPath)
        {
            this.configPath   = configPath;
            this.agentsPath   = agentsPath;
            this.commandsPath = commandsPath;

            // create discord client
            Discord                  = new DiscordSocketClient();
            Discord.JoinedGuild     += Discord_JoinedGuild;
            Discord.LeftGuild       += Discord_LeftGuild;
            Discord.MessageReceived += Discord_MessageReceived;
            Discord.Log             += Log;
            Discord.Ready           += Discord_Ready;

            commandService      = new CommandService();
            commandService.Log += Log;
            try {
                CommandsAssembly = Assembly.LoadFile(Path.GetFullPath(commandsPath));
                await commandService.AddModulesAsync(CommandsAssembly);
            } catch (Exception ex) {
                Log(LogSeverity.Error, "Failed to load commands assembly at \"" + commandsPath + "\"", ex);
                return(false);
            }

            // install commands
            ModifyServices(x => x
                           .AddSingleton(Discord)
                           .AddSingleton(commandService)
                           );

            // load config
            if (!ReloadConfig())
            {
                return(false);
            }

            // export embedded bot agent as reference
            if (!Directory.Exists(agentsPath))
            {
                Directory.CreateDirectory(agentsPath);
            }
            File.WriteAllBytes(Path.Combine(agentsPath, "tomoko.json"), Resources.tomoko);

            // load agent
            if (!ReloadAgent())
            {
                return(false);
            }

            // capture console exit
            consoleCtrlHandler = new WinApi.HandlerRoutine(consoleCtrl);
            WinApi.SetConsoleCtrlHandler(consoleCtrlHandler, true);

            // init record device
            if (Config.speakEnabled)
            {
                recordDevice = -1;
                if (Config.speakRecordingDevice != null)
                {
                    var devices = Bass.BASS_RecordGetDeviceInfos();
                    for (int i = 0; i < devices.Length; i++)
                    {
                        if (devices[i].name == Config.speakRecordingDevice)
                        {
                            recordDevice = i;
                            break;
                        }
                    }
                    if (recordDevice < 0)
                    {
                        IEnumerable <string> devicesList = devices.Select(d => d.name);
                        Log(LogSeverity.Error, "Recording device \"" + Config.speakRecordingDevice + "\" not found.\nAvailable recording devices:\n * " + string.Join("\n * ", devicesList) + "\n");
                        return(false);
                    }
                }

                if (!Bass.BASS_RecordInit(recordDevice))
                {
                    Log(LogSeverity.Error, "Failed to init recording device: " + Bass.BASS_ErrorGetCode());
                    return(false);
                }
                recordProc = new RECORDPROC(recordDevice_audioReceived);
            }

            // init playback device
            if (Config.listenEnabled)
            {
                playbackDevice = -1;
                if (Config.listenPlaybackDevice != null)
                {
                    var devices = Bass.BASS_GetDeviceInfos();
                    for (int i = 0; i < devices.Length; i++)
                    {
                        if (devices[i].name == Config.listenPlaybackDevice)
                        {
                            playbackDevice = i;
                            break;
                        }
                    }
                    if (playbackDevice < 0)
                    {
                        IEnumerable <string> devicesList = devices.Select(d => d.name);
                        Log(LogSeverity.Error, "Playback device \"" + Config.listenPlaybackDevice + "\" not found.\nAvailable playback devices:\n * " + string.Join("\n * ", devicesList) + "\n");
                        return(false);
                    }
                }

                if (!Bass.BASS_Init(playbackDevice, SAMPLE_RATE, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero, null))
                {
                    Log(LogSeverity.Error, "Failed to init playback device: " + Bass.BASS_ErrorGetCode());
                    return(false);
                }
                playProc = new STREAMPROC(playbackDevice_audioRequested);
            }

            return(true);
        }
        public BASSPlayer()
        {
            _VizAGC = new DSP_VizAGC();
              _ReplayGainDSP = new DSP_Gain();
              _ASIOEngine = new AsioEngine();

              _StreamWriteProcDelegate = new STREAMPROC(StreamWriteProc);
              _VizRawStreamWriteProcDelegate = new STREAMPROC(VizRawStreamWriteProc);
              _DSOutputStreamWriteProcDelegate = new STREAMPROC(DSOutputStreamWriteProc);
              _MetaTagSyncProcDelegate = new SYNCPROC(StreamMetaTagSyncProc);
              _WasapiProcDelegate = new WASAPIPROC(WasApiProc);

              // Make sure threads are stopped in case Dispose does not get called.
              Application.ApplicationExit += new EventHandler(Application_ApplicationExit);

              _WakeupMainThread = new AutoResetEvent(false);
              _WakeupMonitorThread = new AutoResetEvent(false);
              _WakeupBufferUpdateThread = new AutoResetEvent(false);
              _BufferUpdated = new ManualResetEvent(false);

              _MainThread = new Thread(new ThreadStart(ThreadMain));
              _MonitorThread = new Thread(new ThreadStart(ThreadMonitor));
              _BufferUpdateThread = new Thread(new ThreadStart(ThreadBufferUpdate));

              _MainThread.Name = "PureAudio.Main";
              _MainThread.Start();

              _BufferUpdateThread.Name = "PureAudio.BufferUpdate";
              _BufferUpdateThread.IsBackground = true;
              _BufferUpdateThread.Start();

              _MonitorThread.Name = "PureAudio.Monitor";
              _MonitorThread.IsBackground = true;
              _MonitorThread.Start();
        }
        public HttpInfinitePlaySource(string address, DownloadTypes downloadMode,
            IEventAggregator positionEventAggregator)
        {
            OnGetPosition += RefreshPositions;
            _positionEventAggregator = positionEventAggregator;
            _subscriptionToken = _positionEventAggregator.GetEvent<HttpPositionEvent>().Subscribe(GetReadPosition);
            _downloadType = downloadMode;
            _downloadProcURL = (_downloadType == DownloadTypes.NoDownload)
                ? null
                : new DOWNLOADPROC(DownloadProc);

            Path = address;

            DownloadStream = Bass.BASS_StreamCreateURL(Path, 0,
                BASSFlag.BASS_STREAM_AUTOFREE|BASSFlag.BASS_STREAM_STATUS |BASSFlag.BASS_SAMPLE_FLOAT, _downloadProcURL, IntPtr.Zero);

            BASSError error = Bass.BASS_ErrorGetCode();

            if (DownloadStream == 0)
                throw new ArgumentException("Parameter cannot be null", error.ToString());

            _syncProcMeta = new SYNCPROC(SyncMethodMeta);

            Bass.BASS_ChannelSetSync(DownloadStream, BASSSync.BASS_SYNC_WMA_META, 0, _syncProcMeta, IntPtr.Zero);
            Bass.BASS_ChannelSetSync(DownloadStream, BASSSync.BASS_SYNC_OGG_CHANGE, 0, _syncProcMeta, IntPtr.Zero);
            Bass.BASS_ChannelSetSync(DownloadStream, BASSSync.BASS_SYNC_META, 0, _syncProcMeta, IntPtr.Zero);
            Bass.BASS_ChannelSetSync(DownloadStream, BASSSync.BASS_SYNC_WMA_CHANGE, 0, _syncProcMeta, IntPtr.Zero);

            _previousTags = new List<Tag>();
            Tags = new TrackTags(DownloadStream, SourceType);
            Tags.GetIcyMetaTags(DownloadStream);
            ChannelInfo = Bass.BASS_ChannelGetInfo(DownloadStream);

            if (ProcessMusic())
            {
                _bufferFileStream = new FileStream("RadioBuffer", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                _DSPHandler = new DSPPROC(DSPProc);
                _streamProc = new STREAMPROC(StreamRead);
                DSP = Bass.BASS_ChannelSetDSP(DownloadStream, _DSPHandler, IntPtr.Zero, 0);
                Stream = Bass.BASS_StreamCreate(ChannelInfo.freq, ChannelInfo.chans,
                    BASSFlag.BASS_STREAM_DECODE|BASSFlag.BASS_SAMPLE_FLOAT, _streamProc, IntPtr.Zero);

                Bass.BASS_ChannelPlay(DownloadStream, false);
                Bass.BASS_ChannelSetAttribute(DownloadStream, BASSAttribute.BASS_ATTRIB_VOL, 0);
                StreamFX = BassFx.BASS_FX_TempoCreate(Stream, BASSFlag.BASS_FX_FREESOURCE | BASSFlag.BASS_SAMPLE_FX);
            }
            else
            {
                error = Bass.BASS_ErrorGetCode();
                throw new ArgumentException("Parameter cannot be null", error.ToString());
            }
        }
Esempio n. 27
0
 private PlaybackSession(Controller controller, int channels, int sampleRate, bool isPassThrough)
 {
   _controller = controller;
   _playbackProcessor = _controller.PlaybackProcessor;
   _playbackBuffer = new PlaybackBuffer(controller);
   _upDownMixer = new UpDownMixer();
   _vstProcessor = new VSTProcessor();
   _winAmpDSPProcessor = new WinAmpDSPProcessor(controller);
   _channels = channels;
   _sampleRate = sampleRate;
   _isPassThrough = isPassThrough;
   _streamWriteProcDelegate = OutputStreamWriteProc;
   _state = SessionState.Reset;
 }
Esempio n. 28
0
        /// <summary>
        /// Creates a stream from memory using a custom callback procedure.
        /// </summary>
        /// <param name="frequency">Frequency (sample rate)</param>
        /// <param name="numberOfChannels">Number of channels (mono = 1, stereo = 2)</param>
        /// <param name="useFloatingPoint">Indicates if the channel should use floating point</param>
        /// <param name="streamProc">Handle to the STREAMPROC callback</param>
        /// <returns>Channel object</returns>
        public static Channel CreateStream(int frequency, int numberOfChannels, bool useFloatingPoint, STREAMPROC streamProc)
        {
            // Build flags; add base flags
            BASSFlag flags = BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_STREAM_PRESCAN;
            if (useFloatingPoint)
                flags |= BASSFlag.BASS_SAMPLE_FLOAT;

            // Create file stream
            int handle = Bass.BASS_StreamCreate(frequency, numberOfChannels, flags, streamProc, IntPtr.Zero);
            if (handle == 0)
                Base.CheckForError();
            
            // Return new channel instance
            return new Channel(handle, ChannelType.Memory, true, useFloatingPoint) { sampleRate = frequency };
        }    
Esempio n. 29
0
 public static extern int BASS_StreamCreate(int freq, int chans, BASSFlag flags, STREAMPROC proc, IntPtr user);
Esempio n. 30
0
        /// <summary>
        /// Plays the playlist from the current item index.
        /// </summary>
        public void Play(double initialPosition, bool startPaused)
        {
            try
            {
                if (_isPlaying)
                {
                    if (_currentLoop != null)
                    {
						//Tracing.Log("Player.Play -- Stopping current loop...");
                        StopLoop();
                    }

					//Tracing.Log("Player.Play -- Stopping playback...");
                    Stop();
                }

                RemoveSyncCallbacks();
                _currentLoop = null;
                _positionOffset = 0;
                _currentMixPlaylistIndex = Playlist.CurrentItemIndex;

                // How many channels are left?                
                int channelsToLoad = Playlist.Items.Count - Playlist.CurrentItemIndex;                

                // If there are more than 2, just limit to 2 for now. The other channels are loaded dynamically.
                if (channelsToLoad > 2)
                    channelsToLoad = 2;

                // Check for channels to load
                if (channelsToLoad == 0)
                    throw new Exception("Error in Player.Play: There aren't any channels to play!");

                // Load the current channel and the next channel if it exists
                for (int a = Playlist.CurrentItemIndex; a < Playlist.CurrentItemIndex + channelsToLoad; a++)
                    _playlist.Items[a].Load(_useFloatingPoint);

                // Start decoding first playlist item
                //_decodingService.StartDecodingFile(_playlist.Items[0].AudioFile.FilePath, _positionOffset);

                try
                {
                    // Create the streaming channel (set the frequency to the first file in the list)
					//Tracing.Log("Player.Play -- Creating streaming channel (SampleRate: " + _playlist.CurrentItem.AudioFile.SampleRate + " Hz, FloatingPoint: true)...");

#if IOS
                    _streamProc = new STREAMPROC(StreamCallbackIOS);
#else
                    _streamProc = new STREAMPROC(StreamCallback);
#endif

                    _streamChannel = Channel.CreateStream(_playlist.CurrentItem.AudioFile.SampleRate, 2, _useFloatingPoint, _streamProc);
					//Tracing.Log("Player.Play -- Creating time shifting channel...");
                    _fxChannel = Channel.CreateStreamForTimeShifting(_streamChannel.Handle, true, _useFloatingPoint);
                    //_fxChannel = Channel.CreateStreamForTimeShifting(_streamChannel.Handle, false, _useFloatingPoint);
                    //_fxChannel = _streamChannel;
                }
                catch(Exception ex)
                {
                    // Raise custom exception with information (so the client application can maybe deactivate floating point for example)
                    PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to create the stream channel (" + ex.Message + ").", ex);
                    newEx.Decode = true;
                    newEx.UseFloatingPoint = true;
                    newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
                    throw newEx;
                }

                // Check driver type
                if (_device.DriverType == DriverType.DirectSound)
                {
                    try
                    {
                        // Create mixer stream
						Tracing.Log("Player.Play -- Creating mixer channel (DirectSound)...");
                        _mixerChannel = MixerChannel.CreateMixerStream(_playlist.CurrentItem.AudioFile.SampleRate, 2, _useFloatingPoint, false);
                        _mixerChannel.AddChannel(_fxChannel.Handle);
                        //_mixerChannel = _fxChannel;
                        AddBPMCallbacks();
                    }
                    catch (Exception ex)
                    {   
                        // Raise custom exception with information (so the client application can maybe deactivate floating point for example)
                        PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to create the time shifting channel.", ex);
                        newEx.UseFloatingPoint = true;
                        newEx.UseTimeShifting = true;
                        newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
                        throw newEx;
                    }
                }
#if !IOS && !ANDROID
                else if (_device.DriverType == DriverType.ASIO)
                {
                    try
                    {
                        // Create mixer stream
                        Tracing.Log("Player.Play -- Creating mixer channel (ASIO)...");
                        _mixerChannel = MixerChannel.CreateMixerStream(_playlist.CurrentItem.AudioFile.SampleRate, 2, _useFloatingPoint, true);
                        _mixerChannel.AddChannel(_fxChannel.Handle);
                    }
                    catch (Exception ex)
                    {
                        // Raise custom exception with information (so the client application can maybe deactivate floating point for example)
                        PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to create the time shifting channel.", ex);
                        newEx.DriverType = DriverType.ASIO;
                        newEx.UseFloatingPoint = true;
                        newEx.UseTimeShifting = true;
                        newEx.Decode = true;
                        newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
                        throw newEx;  
                    }
                    
                    // Set floating point
                    BassAsio.BASS_ASIO_ChannelSetFormat(false, 0, BASSASIOFormat.BASS_ASIO_FORMAT_FLOAT);

                    // Create callback
                    asioProc = new ASIOPROC(AsioCallback);

                    try
                    {
                        // Enable and join channels (for stereo output
                        Tracing.Log("Player.Play -- Enabling ASIO channels...");
                        BassAsio.BASS_ASIO_ChannelEnable(false, 0, asioProc, new IntPtr(_mixerChannel.Handle));
                        Tracing.Log("Player.Play -- Joining ASIO channels...");
                        BassAsio.BASS_ASIO_ChannelJoin(false, 1, 0);

                        // Set sample rate
                        Tracing.Log("Player.Play -- Set ASIO sample rates...");
                        BassAsio.BASS_ASIO_ChannelSetRate(false, 0, _playlist.CurrentItem.AudioFile.SampleRate);
                        BassAsio.BASS_ASIO_SetRate(_playlist.CurrentItem.AudioFile.SampleRate);
                    }
                    catch (Exception ex)
                    {
                        // Raise custom exception with information (so the client application can maybe deactivate floating point for example)
                        PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to enable or join ASIO channels.", ex);
                        newEx.DriverType = DriverType.ASIO;
                        newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
                        throw newEx;
                    }

                    // Start playback
                    Tracing.Log("Player.Play -- Starting ASIO buffering...");
                    if (!BassAsio.BASS_ASIO_Start(0))
                    {
                        // Get BASS error
                        BASSError error = Bass.BASS_ErrorGetCode();

                        // Raise custom exception with information (so the client application can maybe deactivate floating point for example)
                        PlayerCreateStreamException newEx = new PlayerCreateStreamException("The player has failed to create the ASIO channel (" + error.ToString() + ").", null);
                        newEx.DriverType = DriverType.ASIO;
                        newEx.UseFloatingPoint = true;
                        newEx.UseTimeShifting = true;
                        newEx.Decode = true;
                        newEx.SampleRate = _playlist.CurrentItem.AudioFile.SampleRate;
                        throw newEx;                        
                    }
                }
                else if (_device.DriverType == DriverType.WASAPI)
                {
                    // Create mixer stream
                    Tracing.Log("Player.Play -- Creating mixer channel (WASAPI)...");
                    _mixerChannel = MixerChannel.CreateMixerStream(_playlist.CurrentItem.AudioFile.SampleRate, 2, true, true);
                    _mixerChannel.AddChannel(_fxChannel.Handle);

                    // Start playback
                    if (!BassWasapi.BASS_WASAPI_Start())
                    {
                        // Get error
                        BASSError error = Bass.BASS_ErrorGetCode();
                        throw new Exception("Player.Play error: Error playing files in WASAPI: " + error.ToString());
                    }
                }
#endif
                // Set initial volume
                _mixerChannel.Volume = Volume;

                // Load 18-band equalizer
				//Tracing.Log("Player.Play -- Creating equalizer (Preset: " + _currentEQPreset + ")...");
                AddEQ(_currentEQPreset);

                // Check if EQ is bypassed
                if (_isEQBypassed)
                {
                    // Reset EQ
					//Tracing.Log("Player.Play -- Equalizer is bypassed; resetting EQ...");
                    ResetEQ();
                }

                // Check if the song must be looped
                if (_repeatType == RepeatType.Song)
                    _playlist.CurrentItem.Channel.SetFlags(BASSFlag.BASS_SAMPLE_LOOP, BASSFlag.BASS_SAMPLE_LOOP);

                long length = _playlist.CurrentItem.Channel.GetLength();
                SetSyncCallback(length);
                _isPlaying = true;

                // Only the DirectSound mode needs to start the main channel since it's not in decode mode.
                if (_device.DriverType == DriverType.DirectSound)
                {
                    // For iOS: This is required to update the AirPlay/remote player status
                    Base.Start();

                    // Start playback
					//Tracing.Log("Player.Play -- Starting DirectSound playback...");
                    _mixerChannel.Play(false);

                    if (startPaused)
                    {
                        if(initialPosition > 0)
                            SetPosition(initialPosition);

                        Base.Pause();
                    }

                    _isPaused = startPaused;
                }

//                StartEncode(EncoderType.OGG);
//                StartCast(new CastServerParams()
//                {
//                    Bitrate = 128,
//                    Name = "Sessions Test Server",
//                    Url = "localhost:8000",
//                    Password = "******"
//                });

                // Raise audio file finished event (if an event is subscribed)
                if (OnPlaylistIndexChanged != null)
                {
                    PlayerPlaylistIndexChangedData data = new PlayerPlaylistIndexChangedData();
                    data.IsPlaybackStopped = false;
                    data.AudioFileStarted = _playlist.CurrentItem.AudioFile;
                    data.PlaylistName = "New playlist 1";
                    data.PlaylistCount = _playlist.Items.Count;
                    data.PlaylistIndex = _playlist.CurrentItemIndex; 
                    if (Playlist.CurrentItemIndex < Playlist.Items.Count - 2)
                        data.NextAudioFile = Playlist.Items[Playlist.CurrentItemIndex + 1].AudioFile;
                    OnPlaylistIndexChanged(data);
                }
            }
            catch (Exception ex)
            {
                Tracing.Log("Player.Play error: " + ex.Message + "\n" + ex.StackTrace);
                throw;
            }
        }
Esempio n. 31
0
 internal int StreamCreate(int freq, int chans, BASSFlag Flags, STREAMPROC proc, IntPtr user)
 {
   lock (_syncRoot)
   {
     return Bass.BASS_StreamCreate(freq, chans, Flags, proc, user);
   }
 }
Esempio n. 32
0
 private static extern IntPtr _BASS_StreamCreate(uint freq, uint chans, uint flags, STREAMPROC proc, IntPtr user);
Esempio n. 33
0
 public static extern int BASS_StreamCreate(int freq, int chans, BASSFlag flags, STREAMPROC proc, IntPtr user);
Esempio n. 34
0
        /// <summary>
        /// Starts the playback of an audio file.
        /// </summary>
        /// <param name="filePath">Audio file path</param>
        public void Play(string filePath)
        {
            // Check if the file exists
            if (!File.Exists(filePath))
            {
                throw new Exception("Error in TestDevice.Play: The file doesn't exist!");
            }
            
            // Check driver type
            if (device.DriverType == DriverType.DirectSound)
            {
                // Create stream
                stream = Bass.BASS_StreamCreateFile(filePath, 0, 0, BASSFlag.BASS_DEFAULT);
                if (stream == 0)
                {
                    // Get error
                    BASSError error = Bass.BASS_ErrorGetCode();
                    throw new Exception("Error playing TestDevice: " + error.ToString());
                }

                // Get stream info
                BASS_CHANNELINFO channelInfo = Bass.BASS_ChannelGetInfo(stream);

                // Create callback
                streamProc = new STREAMPROC(DirectSoundCallback);

                // Create master stream
                streamDirectSound = Bass.BASS_StreamCreate(channelInfo.freq, channelInfo.chans, BASSFlag.BASS_DEFAULT, streamProc, IntPtr.Zero);

                // Start playback
                if(!Bass.BASS_ChannelPlay(stream, false))
                {
                    // Get error
                    BASSError error = Bass.BASS_ErrorGetCode();
                    throw new Exception("Error playing TestDevice: " + error.ToString());
                }
            }
#if !IOS && !ANDROID
            else if (device.DriverType == DriverType.ASIO)
            {
                // Create stream
                stream = Bass.BASS_StreamCreateFile(filePath, 0, 0, BASSFlag.BASS_STREAM_DECODE);                
                if (stream == 0)
                {
                    // Get error
                    BASSError error = Bass.BASS_ErrorGetCode();
                    throw new Exception("Error playing TestDevice: " + error.ToString());
                }

                // Create callback
                asioProc = new ASIOPROC(AsioCallback);

                // Create channel
                BassAsio.BASS_ASIO_ChannelEnable(false, 0, asioProc, new IntPtr(stream));
                BassAsio.BASS_ASIO_ChannelJoin(false, 1, 0);

                // Start playback
                if (!BassAsio.BASS_ASIO_Start(0))
                {
                    // Get error
                    BASSError error = Bass.BASS_ErrorGetCode();
                    throw new Exception("Error playing TestDevice: " + error.ToString());
                }
            }
            else if (device.DriverType == DriverType.WASAPI)
            {
                // Create stream
                stream = Bass.BASS_StreamCreateFile(filePath, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT);
                if (stream == 0)
                {
                    // Get error
                    BASSError error = Bass.BASS_ErrorGetCode();
                    throw new Exception("Error playing TestDevice: " + error.ToString());
                }

                // Start playback
                if (!BassWasapi.BASS_WASAPI_Start())
                {
                    // Get error
                    BASSError error = Bass.BASS_ErrorGetCode();
                    throw new Exception("Error playing TestDevice: " + error.ToString());
                }
            }
#endif
        }