Exemplo n.º 1
0
 /// <summary>
 /// </summary>
 /// <param name="playlistService">The playlist service.</param>
 /// <param name="player">The player.</param>
 /// <param name="publicTransport">The public transport.</param>
 /// <param name="configurationManager">The configuration manager.</param>
 /// <param name="hotkeyService">The hotkey service.</param>
 public NonManagingPlayerService(IPlaylistService playlistService,
                                 IAudioPlayer player,
                                 IPublicTransport publicTransport,
                                 IConfigurationManager configurationManager,
                                 IGlobalHotkeyService hotkeyService)
 {
     state = PlayingState.Stopped;
     this.playlistService      = Guard.IsNull(() => playlistService);
     this.player               = Guard.IsNull(() => player);
     this.publicTransport      = Guard.IsNull(() => publicTransport);
     this.configurationManager = Guard.IsNull(() => configurationManager);
     this.hotkeyService        = Guard.IsNull(() => hotkeyService);
     Subscribe();
     prebufferSongs                 = configurationManager.GetValue("PrebufferSongs", 2, "PlayerService");
     PlayNextThreshold              = configurationManager.GetValue("PlayNextThreshnoldMs", 500d, "PlayerService");
     TrackInterchangeCrossfadeTime  = configurationManager.GetValue("TrackInterchangeCrossfadeTimeMs", 500d, "PlayerService");
     TrackInterchangeCrossFadeSteps = configurationManager.GetValue("TrackInterchangeCrossfadeSteps", 50, "PlayerService");
     maxBackStack              = configurationManager.GetValue("MaxBackStack", 2000, "PlayerService");
     LastPlayed                = configurationManager.GetValue("PlayerService.LastPlayed", Guid.Empty, KnownConfigSections.Hidden);
     LastPlayedOffset          = configurationManager.GetValue("PlayerService.LastPlayedOffset", 0d, KnownConfigSections.Hidden);
     VolumeValue               = configurationManager.GetValue("PlayerService.Volume", 1f, KnownConfigSections.Hidden);
     preBuffered               = new List <TrackContainer>(prebufferSongs.Value);
     backStack                 = new List <TrackContainer>(maxBackStack.Value);
     VolumeValue.ValueChanged += VolumeValueOnValueChanged;
     RegisterHotkeys();
     LoadLastPlayed();
     UpdateState();
     SendProgress();
 }
Exemplo n.º 2
0
 public StageReadyUseCase(AnswerList answerList,
                          IAnswerRenderer answerRenderer,
                          IAudioPlayer audioPlayer,
                          IInfoEntity infoEntity,
                          IKeyboardEntity keyboardEntity,
                          IMainStateEntity mainStateEntity,
                          IPhotonChatPrcRequester photonChatPrcRequester,
                          IPlayerEntity playerEntity,
                          IReadOnlyList <IKeyboardKeyRenderer> keyboardKeyRendererList,
                          IReadOnlyList <IStageRenderer> stageRendererList,
                          IStageEntity stageEntity,
                          IStageReadyHandler stageReadyHandler,
                          IStageReadyPlayerListRenderer stageReadyPlayerListRenderer,
                          IStageReadyRpcRequester stageReadyRpcRequester,
                          ITimerEntity timerEntity)
 {
     AnswerList                   = answerList;
     AnswerRenderer               = answerRenderer;
     AudioPlayer                  = audioPlayer;
     InfoEntity                   = infoEntity;
     KeyboardEntity               = keyboardEntity;
     MainStateEntity              = mainStateEntity;
     PhotonChatPrcRequester       = photonChatPrcRequester;
     PlayerEntity                 = playerEntity;
     KeyboardKeyRendererList      = keyboardKeyRendererList;
     StageRendererList            = stageRendererList;
     StageEntity                  = stageEntity;
     StageReadyHandler            = stageReadyHandler;
     StageReadyPlayerListRenderer = stageReadyPlayerListRenderer;
     StageReadyRpcRequester       = stageReadyRpcRequester;
     TimerEntity                  = timerEntity;
 }
 public BirdSoundComponent(IAudioPlayer audioPlayer, ISound wingSound, ISound hitSound, ISound dieSound)
 {
     _audioPlayer = audioPlayer;
     _wingSound   = wingSound;
     _hitSound    = hitSound;
     _dieSound    = dieSound;
 }
Exemplo n.º 4
0
        public ScreenShotModel(VideoSourcesViewModel VideoSourcesViewModel,
                               ISystemTray SystemTray,
                               IRegionProvider RegionProvider,
                               IMainWindow MainWindow,
                               IVideoSourcePicker SourcePicker,
                               IAudioPlayer AudioPlayer,
                               IEnumerable <IImageWriterItem> ImageWriters,
                               Settings Settings,
                               LanguageManager Loc,
                               IPlatformServices PlatformServices)
        {
            _videoSourcesViewModel = VideoSourcesViewModel;
            _systemTray            = SystemTray;
            _regionProvider        = RegionProvider;
            _mainWindow            = MainWindow;
            _sourcePicker          = SourcePicker;
            _audioPlayer           = AudioPlayer;
            _settings         = Settings;
            _loc              = Loc;
            _platformServices = PlatformServices;

            AvailableImageWriters = ImageWriters.ToList();

            if (!AvailableImageWriters.Any(M => M.Active))
            {
                AvailableImageWriters[0].Active = true;
            }
        }
Exemplo n.º 5
0
        protected PlaylistCommandBase(
            IPlaylist playlist, IMessenger messenger, IAudioPlayer player, Func<IPlaylist, Track> trackSelectFunc)
        {
            if (playlist == null)
            {
                throw new ArgumentNullException("playlist");
            }

            if (messenger == null)
            {
                throw new ArgumentNullException("messenger");
            }

            if (player == null)
            {
                throw new ArgumentNullException("player");
            }

            if (trackSelectFunc == null)
            {
                throw new ArgumentNullException("trackSelectFunc");
            }

            this.playlist = playlist;
            this.player = player;
            this.trackSelectFunc = trackSelectFunc;

            // Need to refresh after adding, removing, shuffling any tracks in
            // the mix. The prev/next track may no longer exist.
            messenger.Register<PlayerLoadedEvent>(this, OnMixChanged);
            messenger.Register<TrackAddedToMixEvent>(this, OnMixChanged);
            messenger.Register<TrackRemovedFromMixEvent>(this, OnMixChanged);
            messenger.Register<TracksRemovedFromMixEvent>(this, OnMixChanged);
            messenger.Register<MixUnlockedEvent>(this, OnMixChanged);
        }
 /// <summary>
 /// Initializes a new instance of PlayCommandExecuter
 /// </summary>
 /// <param name="speechGenerator">AudioPlayer object used to play audio files</param>
 public SpgPlayCommandExecuter(IAudioPlayer audioPlayer)
     : base("spg_play")
 {
     if (audioPlayer == null)
         throw new ArgumentNullException();
     this.audioPlayer = audioPlayer;
 }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a new ViewModel for the specified <see cref="Route"/>.
        /// </summary>
        /// <param name="route">The <see cref="Route"/> the ViewModel is created for.</param>
        public RouteDetailsPageViewModel(Route route)
        {
            Title          = route.Name;
            Description    = route.Audio?.Caption;
            Distance       = string.Format(Strings.RouteDetailsPageViewModel_Distance, route.Distance);
            Duration       = string.Format(Strings.RouteDetailsPageViewModel_Duration, route.Duration / 60);
            ReadOutCaption = Strings.RouteDetailsPage_PlayAudio;
            Tags           = new ObservableCollection <RouteTag>(route.Tags);
            SetRouteImage(route);
            StartRouteCommand = new Command(StartRoute);
            StartDescriptionPlaybackCommand = new Command(StartDescriptionPlayback);

            Tabs = new ObservableCollection <string> {
                Strings.RouteDetailsPageViewModel_Description, Strings.RouteDetailsPageViewModel_Map
            };
            GpsLocation      = IoCManager.Resolve <ILocationManager>().LastKnownLocation?.ToGeoLocation() ?? new GeoLocation(0, 0);
            DetailsRoute     = route;
            ShowDetailsRoute = true;

            // init the audio button
            audioPlayer = IoCManager.Resolve <IAudioPlayer>();
            audioPlayer.CurrentAudio      = route.Audio;
            audioPlayer.AudioTitle        = route.Name;
            audioPlayer.IsPlayingChanged += AudioPlayerOnIsPlayingChanged;
        }
Exemplo n.º 8
0
 public MIDAUX(IAudioPlayer player)
     : base(player)
 {
     Radio.OnOffChanged += Radio_OnOffChanged;
     Manager.AddMessageReceiverForSourceDevice(DeviceAddress.Radio, ProcessRadioMessage);
     Manager.AfterMessageSent += Manager_AfterMessageSent;
 }
        protected void Update()
        {
            IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();
            IWorkflowManager      workflowManager      = ServiceRegistration.Get <IWorkflowManager>();
            IPlayerContext        pcPrimary            = playerContextManager.PrimaryPlayerContext;
            IPlayer      primaryPlayer = pcPrimary == null ? null : pcPrimary.CurrentPlayer;
            IImagePlayer pp            = primaryPlayer as IImagePlayer;
            IVideoPlayer vp            = primaryPlayer as IVideoPlayer;
            IAudioPlayer ap            = primaryPlayer as IAudioPlayer;
            bool         visible       = (pp != null || vp != null || ap != null) &&
                                         !workflowManager.IsStateContainedInNavigationStack(pcPrimary.FullscreenContentWorkflowStateId);
            IResourceString displayTitleRes;

            if (ap != null)
            {
                displayTitleRes = LocalizationHelper.CreateResourceString(Consts.RES_AUDIO_VISUALIZATION);
            }
            else if (vp != null)
            {
                displayTitleRes = LocalizationHelper.CreateStaticString(
                    LocalizationHelper.CreateResourceString(Consts.RES_FULLSCREEN_VIDEO).Evaluate(vp.Name));
            }
            else
            {
                displayTitleRes = LocalizationHelper.CreateResourceString(Consts.RES_FULLSCREEN_IMAGE);
            }
            lock (_syncObj)
            {
                _isVisible            = visible;
                _displayTitleResource = displayTitleRes;
            }
            FireStateChanged();
        }
Exemplo n.º 10
0
        public void Init(
            IBrain brain,
            IVideoProvider videoProvider,
            IVideoRecorder videoRecorder,
            IAudioRecorder audioRecorder,
            IAudioPlayer audioPlayer,
            IAudioRepository audioRepository)
        {
            this.brain         = brain;
            this.videoProvider = videoProvider;
            this.videoRecorder = videoRecorder;
            this.audioRecorder = audioRecorder;

            var frameObserver           = new FrameObserver(brain);
            var frameRecognizedObserver = new FrameRecognizedObserver(audioPlayer, audioRepository);

            recognizeAvailableFrameSubscription = videoProvider.FrameAvailable.Subscribe(frameObserver);

            this.lifetimeStreams = new CompositeDisposable
            {
                brain.FrameRecognized.Subscribe(frameRecognizedObserver),
                videoRecorder.RecordingAvailable.Subscribe(new VideoPublisher(brain)),
                audioRecorder.RecordingAvailable.Subscribe(new AudioPublisher(audioRepository))
            };
        }
        protected virtual void Awake()
        {
            codec = GetCodec();

            microphone = GetComponent <AudioInputDeviceBase>();
            speaker    = GetComponent(typeof(IAudioPlayer)) as IAudioPlayer;

            if (microphone == null)
            {
                Debug.LogError("No audio input component attached to speaker", this);
                return;
            }

            if (speaker == null)
            {
                Debug.LogError("No audio output component attached to speaker", this);
                return;
            }

            if (IsLocal)
            {
                microphone.OnAudioBufferReady += this.OnMicrophoneDataReady;
                microphone.StartRecording();
            }
        }
Exemplo n.º 12
0
        void startPlayback(AudioBufferStream stream)
        {
            stopCurrentItem();
            IPlayer player = new AudioPlayer(new PlayerSettings(stream));

            currentAudioPlayer = player as IAudioPlayer;
            IPlayerFactory savedFactory = g_Player.Factory;

            g_Player.Factory = new PlayerFactory(player);
            isAudioPlaying   = g_Player.Play(AudioPlayer.AIRPLAY_DUMMY_FILE, g_Player.MediaType.Music);
            g_Player.Factory = savedFactory;

            if (!isAudioPlaying)
            {
                currentAudioPlayer = null;
                return;
            }
            //Mediaportal sets the metadata skin properties internally, we overwrite them after a small delay
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Thread.Sleep(SKIN_PROPERTIES_UPDATE_DELAY);
                invoke(delegate()
                {
                    setMetaData();
                    setCover();
                    setDuration();
                }, false);
            });
        }
Exemplo n.º 13
0
 public BordmonitorAUX(IAudioPlayer player)
     : base(player)
 {
     Radio.OnOffChanged += Radio_OnOffChanged;
     Manager.AddMessageReceiverForSourceDevice(DeviceAddress.Radio, ProcessRadioMessage);
     Manager.AddMessageReceiverForDestinationDevice(DeviceAddress.Radio, ProcessToRadioMessage);
 }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ComponentBase" /> class.
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="playlistService">The playlist service.</param>
 /// <param name="player">The player.</param>
 /// <param name="publicTransport">The public transport.</param>
 /// <param name="configurationManager">The configuration manager.</param>
 /// <param name="hotkeyService">The hotkey service.</param>
 public NonManagingPlayerService(ILogger logger,
                                 IPlaylistService playlistService,
                                 IAudioPlayer player,
                                 IPublicTransport publicTransport,
                                 IConfigurationManager configurationManager,
                                 IGlobalHotkeyService hotkeyService)
     : base(logger)
 {
     playlistService.Guard("playlistService");
     player.Guard("player");
     publicTransport.Guard("publicTransport");
     configurationManager.Guard("configurationManager");
     state = PlayingState.Stopped;
     this.playlistService      = playlistService;
     this.player               = player;
     this.publicTransport      = publicTransport;
     this.configurationManager = configurationManager;
     this.hotkeyService        = hotkeyService;
     publicTransport.ApplicationEventBus.Subscribe <PlaylistUpdatedEvent>(OnPlaylistUpdated);
     publicTransport.ApplicationEventBus.Subscribe <ShuffleChangedEvent>(OnShuffleChanged);
     prebufferSongs                 = configurationManager.GetValue("PlayerService.PrebufferSongs", 2);
     PlayNextThreshold              = configurationManager.GetValue("PlayerService.PlayNextThreshnoldMs", 500d);
     TrackInterchangeCrossfadeTime  = configurationManager.GetValue("PlayerService.TrackInterchangeCrossfadeTimeMs", 500d);
     TrackInterchangeCrossFadeSteps = configurationManager.GetValue("PlayerService.TrackInterchangeCrossfadeSteps", 50);
     maxBackStack = configurationManager.GetValue("PlayerService.MaxBackStack", 2000);
     preBuffered  = new List <TrackContainer>(prebufferSongs.Value);
     backStack    = new List <TrackContainer>(maxBackStack.Value);
     RegisterHotkeys();
 }
Exemplo n.º 15
0
 public Playlist(IAudioPlayer player, ICurrentMixProvider mixProvider, IMessenger messenger)
 {
     if (mixProvider == null) throw new ArgumentNullException("mixProvider");
     if (messenger == null) throw new ArgumentNullException("messenger");
     this.player = player;
     this.mixProvider = mixProvider;
 }
Exemplo n.º 16
0
 protected override void OnDisappearing()
 {
     if (audioPlayer != null)
     {
         audioPlayer.Stop();
         audioPlayer = null;
     }
 }
Exemplo n.º 17
0
        public CDChanger(IAudioPlayer player)
            : base(player)
        {
            Manager.AddMessageReceiverForDestinationDevice(DeviceAddress.CDChanger, ProcessCDCMessage);

            announceThread = new Thread(announce);
            announceThread.Start();
        }
Exemplo n.º 18
0
 /// <summary>
 /// Adds the specified player to the collection.
 /// </summary>
 /// <param name="player">The player.</param>
 public void Add(IAudioPlayer player)
 {
     lock (_syncRoot)
     {
         player.Disposed += this.Player_Disposed;
         this.Players.Add(player);
     }
 }
Exemplo n.º 19
0
        public VoiceEnrollmentPageViewModel(INavigationService navigationService, IAudioRecorder audioRecorder, IAudioPlayer audioPlayer) : base(navigationService)
        {
            _audioRecorder = audioRecorder;
            _audioPlayer   = audioPlayer;
            _myVoiceIt     = new VoiceIt2("key_140b7c835a984de2a4921ea57d128245", "tok_c3d96357247149479e5b13375c13e124");

            RecordVoiceText = "Start Recording";
        }
 public LocalSongListActions(SongListViewModel viewModel)
 {
     fileManager = new FirebaseStorageFileManager();
     fileManager.OnFileDownloaded += FileManager_OnFileDownloaded;
     audioPlayer    = DependencyService.Get <IAudioPlayer>();
     hud            = DependencyService.Get <IHud>();
     this.viewModel = viewModel;
 }
Exemplo n.º 21
0
        public void SetUp()
        {
            _audioPlayer = Substitute.For <IAudioPlayer>();
            var audioBackend = Substitute.For <IAudioBackend>();

            audioBackend.AudioPlayer.Returns(_audioPlayer);
            _audioSystem = new AudioSystem(audioBackend);
        }
Exemplo n.º 22
0
 public HostileRunState(int pEntityID, IAnimator pAnimator, IAudioPlayer pAudioPlayer)
 {
     _animator    = pAnimator;
     _audioPlayer = pAudioPlayer;
     // INSTANTIATE _frameTime
     _frameTime = 0.009f;
     _entityUID = pEntityID;
 }
Exemplo n.º 23
0
        private async void Init()
        {
            Player = new AudioGraphPlayer();
            //Player = new BassAudioPlayer();
            var selectedFile = await SelectPlaybackFile();

            Player.CurrentPlayingFile = selectedFile;
        }
Exemplo n.º 24
0
        public SystemTray(Func <TaskbarIcon> TaskbarIcon, Settings Settings, IAudioPlayer AudioPlayer)
        {
            _trayIcon    = TaskbarIcon;
            _settings    = Settings;
            _audioPlayer = AudioPlayer;

            _notificationStack.Opacity = 0;
        }
Exemplo n.º 25
0
 public MIDAUX(IAudioPlayer player)
     : base(player)
 {
     Manager.AddMessageReceiverForSourceDevice(DeviceAddress.Radio, ProcessRadioMessage);
     Manager.AddMessageReceiverForDestinationDevice(DeviceAddress.Radio, ProcessToRadioMessage);
     Manager.AfterMessageSent += Manager_AfterMessageSent;
     InstrumentClusterElectronics.IgnitionStateChanged += InstrumentClusterElectronics_IgnitionStateChanged;
 }
Exemplo n.º 26
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="TrackContainer" /> class.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="file">The file.</param>
        public TrackContainer(IAudioPlayer player, StorableTaggedFile file)
        {
            player.Guard("player");
            file.Guard("file");

            this.player = player;
            File        = file;
        }
Exemplo n.º 27
0
        public CDChanger(IAudioPlayer player)
            : base(player)
        {
            Manager.AddMessageReceiverForDestinationDevice(DeviceAddress.CDChanger, ProcessCDCMessage);

            announceThread = new Thread(announce);
            announceThread.Start();
        }
Exemplo n.º 28
0
 //current state
 public PreviewThreadLauncher(IVideoPlayer player, IAudioPlayer playerAudio, IVidkaOpContext editor)
 {
     this.player = player;
     this.playerAudio = playerAudio;
     this.editor = editor;
     mutex = new PreviewThreadMutex();
     ticker = new Timer();
     ticker.Tick += PlaybackTickerFunc;
 }
Exemplo n.º 29
0
        public BananaTreeGenerator(Transform target, GameSettings settings, IAudioPlayer audioPlayer)
        {
            _target           = target;
            _settings         = settings;
            _audioPlayer      = audioPlayer;
            _createdInstances = new BananaTreeLogic[settings.Actor.SpawnPoints.Length];

            GenerateBananaTrees();
        }
Exemplo n.º 30
0
        public DiscJockey(IConfigSettings configSettings, IAudioPlayer audioPlayer, SpeechMaker speechMaker)
        {
            _audioPlayer      = audioPlayer;
            _speechMaker      = speechMaker;
            _brokenBuildSound = configSettings.BrokenBuildSound;
            _fixedBuildSound  = configSettings.FixedBuildSound;

            configSettings.AddObserver(this);
        }
Exemplo n.º 31
0
 /// <summary>
 /// Constructor for PlayerIdleState
 /// </summary>
 /// <param name="pAnimator"></param>
 /// <param name="pAudioPlayer"></param>
 /// <param name="pArgs"></param>
 public PlayerIdleState(int pEntityID, IAnimator pAnimator, IAudioPlayer pAudioPlayer, IKeyboardInput pArgs)
 {
     _animator    = pAnimator;
     _audioPlayer = pAudioPlayer;
     _args        = pArgs;
     // INSTANTIATE _frameTime
     _frameTime = 0.009f;
     _entityUID = pEntityID;
 }
Exemplo n.º 32
0
 public SFXController(
     Config.BotConfiguration botConfig,
     ISoundEffectSystem soundEffectSystem,
     IAudioPlayer audioPlayer)
 {
     this.botConfig         = botConfig;
     this.soundEffectSystem = soundEffectSystem;
     this.audioPlayer       = audioPlayer;
 }
Exemplo n.º 33
0
        public DiscJockey(IConfigSettings configSettings, IAudioPlayer audioPlayer, SpeechMaker speechMaker)
        {
            _audioPlayer = audioPlayer;
            _speechMaker = speechMaker;
            _brokenBuildSound = configSettings.BrokenBuildSound;
            _fixedBuildSound = configSettings.FixedBuildSound;

            configSettings.AddObserver(this);
        }
Exemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of AplayCommandExecuter
 /// </summary>
 /// <param name="speechGenerator">AudioPlayer object used to play audio files</param>
 public SpgAplayCommandExecuter(IAudioPlayer audioPlayer)
     : base("spg_aplay")
 {
     if (audioPlayer == null)
     {
         throw new ArgumentNullException();
     }
     this.audioPlayer = audioPlayer;
 }
Exemplo n.º 35
0
 public PlayerDamageHandler(
     Player player,
     Settings settings,
     IAudioPlayer audioPlayer)
 {
     _audioPlayer = audioPlayer;
     _settings    = settings;
     _player      = player;
 }
Exemplo n.º 36
0
        void player_IsPlayingChanged(IAudioPlayer sender, AudioPlayerIsPlayingStatusEventArgs args)
        {
            var e = PlayerIsPlayingChanged;

            if (e != null)
            {
                e(sender, args);
            }
        }
 public SaveViewModel(IAudioPlayer audioPlayer)
 {
     this.SampleAggregator = new SampleAggregator();
     SampleAggregator.NotificationCount = 800; // gets set correctly later on
     this.audioPlayer = audioPlayer;
     this.SaveCommand = new RelayCommand(() => Save());
     this.SelectAllCommand = new RelayCommand(() => SelectAll());
     this.PlayCommand = new RelayCommand(() => Play());
     this.StopCommand = new RelayCommand(() => Stop());
     this.AutoTuneCommand = new RelayCommand(() => OnAutoTune());
     Messenger.Default.Register<ShuttingDownMessage>(this, (message) => OnShuttingDown(message));
 }
        public BuildTransitionSoundPlayer(IProjectMonitor monitor, IAudioPlayer audioPlayer, AudioFiles configuration)
        {
            this.audioPlayer = audioPlayer;

            if (configuration != null)
            {
                soundFileLookup[BuildTransition.Broken] = configuration.BrokenBuildSound;
                soundFileLookup[BuildTransition.Fixed] = configuration.FixedBuildSound;
                soundFileLookup[BuildTransition.StillFailing] = configuration.StillFailingBuildSound;
                soundFileLookup[BuildTransition.StillSuccessful] = configuration.StillSuccessfulBuildSound;
            }

            monitor.BuildOccurred += new MonitorBuildOccurredEventHandler(Monitor_BuildOccurred);
        }
 public TrackLibraryItemViewModelFactory(
     IMessenger messenger, 
     IAudioPlayer player, 
     QuickEditBpmCommand quickEditBpmCommand, 
     QuickEditHarmonicKeyCommand quickEditHarmonicKeyCommand, 
     PlayPauseTrackCommand playPauseCommand)
 {
     if (messenger == null) throw new ArgumentNullException("messenger");
     if (player == null) throw new ArgumentNullException("player");
     if (quickEditBpmCommand == null) throw new ArgumentNullException("quickEditBpmCommand");
     if (quickEditHarmonicKeyCommand == null) throw new ArgumentNullException("quickEditHarmonicKeyCommand");
     if (playPauseCommand == null) throw new ArgumentNullException("playPauseCommand");
     this.messenger = messenger;
     this.player = player;
     this.quickEditBpmCommand = quickEditBpmCommand;
     this.quickEditHarmonicKeyCommand = quickEditHarmonicKeyCommand;
     this.playPauseCommand = playPauseCommand;
 }
Exemplo n.º 40
0
 protected override void ShowPlayerStatus(IAudioPlayer player, bool isPlaying)
 {
     var s = TextWithIcon(isPlaying ? CharIcons.Play : CharIcons.Pause, player.Name);
     ShowPlayerStatus(player, s);
 }
Exemplo n.º 41
0
 protected override void ShowPlayerStatus(IAudioPlayer player, string status, PlayerEvent playerEvent)
 {
     if (!IsEnabled)
     {
         return;
     }
     bool showAfterWithDelay = false;
     if (StringHelpers.IsNullOrEmpty(status))
     {
         status = player.Name;
     }
     switch (playerEvent)
     {
         case PlayerEvent.Next:
             status = TextWithIcon(CharIcons.Next, status);
             showAfterWithDelay = true;
             break;
         case PlayerEvent.Prev:
             status = TextWithIcon(CharIcons.Prev, status);
             showAfterWithDelay = true;
             break;
         case PlayerEvent.Playing:
             status = TextWithIcon(CharIcons.Play, status);
             break;
         case PlayerEvent.Current:
             status = TextWithIcon(CharIcons.SelectedArrow, status);
             break;
         case PlayerEvent.Voice:
             status = TextWithIcon(CharIcons.Voice, status);
             break;
         case PlayerEvent.Settings:
             status = TextWithIcon(CharIcons.Voice, status);
             showAfterWithDelay = true;
             break;
     }
     ShowPlayerStatus(player, status);
     if (showAfterWithDelay)
     {
         ShowPlayerStatusWithDelay(player);
     }
 }
        public ListenPage()
        {
            InitializeComponent();

            if (Device.OS == TargetPlatform.iOS)
            {
                sourceHighBandwidth = new Uri("http://live.kvmr.org:8000/aac96");
                sourceLowBandwidth = new Uri("http://live.kvmr.org:8000/aac32");
            }
            else if (Device.OS == TargetPlatform.Android)
            {
                sourceHighBandwidth = new Uri("http://live2.kvmr.org:8190/kvmr");
                sourceLowBandwidth = new Uri("http://live.kvmr.org:8000/dial");
            }

            useHighBandwidth = Helpers.Settings.BandwidthSwitchState;
            if (useHighBandwidth)
            {
                source = sourceHighBandwidth;
            }
            else
            {
                source = sourceLowBandwidth;
            }

            playStopBtn.Clicked += OnPlayStopBtnClicked;

            TapGestureRecognizer launchSettingsImageTGR = new TapGestureRecognizer();
            launchSettingsImageTGR.Tapped += DisplaySettings;
            launchSettingsImage.GestureRecognizers.Add(launchSettingsImageTGR);

            audioPlayer = DependencyService.Get<IAudioPlayer>();

            MessagingCenter.Subscribe<AudioBeginInterruptionMessage>(this, "AudioBeginInterruption", 
                OnAudioBeginInterruption);
            MessagingCenter.Subscribe<HeadphonesUnpluggedMessage>(this, "HeadphonesUnplugged", 
                OnHeadphonesUnplugged);
            if (Device.OS == TargetPlatform.iOS)
            {
                MessagingCenter.Subscribe<LostStreamMessage>(this, "LostStream", 
                    OnLostStream);
                MessagingCenter.Subscribe<Page>(this, "AudioEndInterruption",
                    OnAudioEndInterruption);
                MessagingCenter.Subscribe<Page>(this, "RemoteControlTogglePlayPause",
                    OnRemoteControlTogglePlayPause);
                MessagingCenter.Subscribe<Page>(this, "RemoteControlPauseOrStop",
                    OnRemoteControlPauseOrStop);
                MessagingCenter.Subscribe<Page>(this, "RemoteControlPlayOrPreviousTrackOrNextTrack",
                    OnRemoteControlPlayOrPreviousTrackOrNextTrack);
                MessagingCenter.Subscribe<Page>(this, "BandwidthSwitchToggled",
                    OnBandwidthSwitchToggled);
            }
            else if (Device.OS == TargetPlatform.Android)
            {
                MessagingCenter.Subscribe<BufferingStartMessage>(this, "BufferingStart", 
                    OnBufferingStart);
                MessagingCenter.Subscribe<BufferingEndMessage>(this, "BufferingEnd", 
                    OnBufferingEnd);
                MessagingCenter.Subscribe<RemoteControlPlayMessage>(this, "RemoteControlPlay", 
                    OnRemoteControlPlay);
                MessagingCenter.Subscribe<PlayerStartedMessage>(this, "PlayerStarted", 
                    OnPlayerStarted);
                MessagingCenter.Subscribe<PlayerStoppedMessage>(this, "PlayerStopped", 
                    OnPlayerStopped);
            }
        }
Exemplo n.º 43
0
 protected void ShowPlayerStatus(IAudioPlayer player)
 {
     // TODO move to player interface
     #if !MF_FRAMEWORK_VERSION_V4_1
     if (player is BluetoothWT32 && !((BluetoothWT32)player).IsConnected)
     {
         ShowPlayerStatus(player, Localization.Current.Disconnected, PlayerEvent.Wireless);
     }
     else
     #endif
     {
         ShowPlayerStatus(player, player.IsPlaying);
     }
 }
Exemplo n.º 44
0
        protected void ShowPlayerStatusWithDelay(IAudioPlayer player)
        {
            if (displayStatusDelayTimer != null)
            {
                displayStatusDelayTimer.Dispose();
                displayStatusDelayTimer = null;
            }

            displayStatusDelayTimer = new Timer(delegate
            {
                ShowPlayerStatus(player);
            }, null, displayStatusDelay, 0);
        }
Exemplo n.º 45
0
 public BordmonitorAUX(IAudioPlayer player)
     : base(player)
 {
     Radio.OnOffChanged += Radio_OnOffChanged;
     Manager.AddMessageReceiverForSourceDevice(DeviceAddress.Radio, ProcessRadioMessage);
 }
 public AudioToVideoAdapter(IAudioPlayer audioPlayer)
 {
     _audioPlayer = audioPlayer;
 }
Exemplo n.º 47
0
        private void WorkerThread()
        {
            bool file = false;
            try
            {
                if (File.Exists(_source))
                {
                    file = true;
                }
            }
            catch
            {

            }

            if (_mFactory == null)
            {
                var args = new List<string>
                    {
                        "-I",
                        "dumy",
                        "--ignore-config",
                        "--no-osd",
                        "--disable-screensaver",
                        "--plugin-path=./plugins",
                        "--novideo"
                    };
                if (file)
                    args.Add("--file-caching=3000");

                try
                {
                    var l2 = args.ToList();
                    l2.AddRange(_arguments);

                    l2= l2.Distinct().ToList();
                    _mFactory = new MediaPlayerFactory(l2.ToArray());
                }
                catch (Exception ex)
                {
                    MainForm.LogExceptionToFile(ex);
                    MainForm.LogMessageToFile("VLC arguments are: " + String.Join(",", args.ToArray()));
                    MainForm.LogMessageToFile("Using default VLC configuration.");
                    _mFactory = new MediaPlayerFactory(args.ToArray());
                }
                GC.KeepAlive(_mFactory);
            }

            if (file)
                _mMedia = _mFactory.CreateMedia<IMediaFromFile>(_source);
            else
                _mMedia = _mFactory.CreateMedia<IMedia>(_source);

            _mMedia.Events.DurationChanged += EventsDurationChanged;
            _mMedia.Events.StateChanged += EventsStateChanged;

            if (_mPlayer != null)
            {
                try
                {
                    _mPlayer.Dispose();
                }
                catch
                {

                }
                _mPlayer = null;
            }

            _mPlayer = _mFactory.CreatePlayer<IAudioPlayer>();
            _mPlayer.Events.TimeChanged += EventsTimeChanged;

            var fc = new Func<SoundFormat, SoundFormat>(SoundFormatCallback);
            _mPlayer.CustomAudioRenderer.SetFormatCallback(fc);
            var ac = new AudioCallbacks { SoundCallback = SoundCallback };
            _mPlayer.CustomAudioRenderer.SetCallbacks(ac);
            _mPlayer.CustomAudioRenderer.SetExceptionHandler(Handler);
            GC.KeepAlive(_mPlayer);

            _needsSetup = true;
            _stopping = false;

            _mPlayer.Open(_mMedia);
            _mMedia.Parse(true);
            _mPlayer.Delay = 0;

            _framesReceived = 0;
            Duration = Time = 0;
            LastFrame = DateTime.MinValue;

            //check if file source (isseekable in _mPlayer is not reliable)
            Seekable = false;
            try
            {
                var p = Path.GetFullPath(_mMedia.Input);
                Seekable = !String.IsNullOrEmpty(p);
            }
            catch (Exception)
            {
                Seekable = false;
            }
            _mPlayer.Play();

            _stopEvent.WaitOne();

            if (!Seekable && !_stopRequested)
            {
                if (AudioFinished != null)
                    AudioFinished(this, ReasonToFinishPlaying.DeviceLost);

            }
            else
            {
                if (AudioFinished != null)
                    AudioFinished(this, ReasonToFinishPlaying.StoppedByUser);
            }

            DisposePlayer();
        }
Exemplo n.º 48
0
 public static void Initialize()
 {
     audioPlayer = new Bass.BassAudioPlayer();
 }
Exemplo n.º 49
0
 protected abstract void ShowPlayerStatus(IAudioPlayer player, string status, PlayerEvent playerEvent);
		public override void Start()
		{
			base.Start();
            Current = this;

			IRelativePanel panel = Platform.Current.Create<IRelativePanel>();
			panel.BackgroundColor = new Color(255, 255, 255, 255);
			AudioPlayer = Core.BaitAndSwitch.Create<IAudioPlayer>(new string[] { "Xamarin.Android", "Xamarin.iOS" });

						IGrid grdMenu = Constantes.CrearMenuVacio();
			panel.Add(grdMenu, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.TopWith);

			IImageButton imgHome = Platform.Current.Create<IImageButton>();
			imgHome.LoadFromUrl(new Uri("http://radioudg.okhosting.com/images-old/icon2--15.png"));
			grdMenu.SetContent(1, 0, imgHome);

			IImageButton imgRegionales = Platform.Current.Create<IImageButton>();
			imgRegionales.LoadFromUrl(new Uri("http://radioudg.okhosting.com/images-old/icon-11.png"));
			imgRegionales.Click += (object sender, EventArgs e) => new RegionalesController().Start();
			grdMenu.SetContent(1, 1, imgRegionales);

			IImageButton imgProgramas = Platform.Current.Create<IImageButton>();
			imgProgramas.LoadFromUrl(new Uri("http://radioudg.okhosting.com/images-old/icon-07.png"));
			imgProgramas.Click += (object sender, EventArgs e) => new ProgramasController().Start();
			grdMenu.SetContent(1, 2, imgProgramas);

			IImageButton imgVirtuales = Platform.Current.Create<IImageButton>();
			imgVirtuales.LoadFromUrl(new Uri("http://radioudg.okhosting.com/images-old/icon-09.png"));
			imgVirtuales.Click += (object sender, EventArgs e) => new VirtualesController().Start();
			grdMenu.SetContent(1, 3, imgVirtuales);

			ILabel lblTitulo = Constantes.CrearTitulo("Radio Universidad De Guadalajara", new Color(255, 255, 212, 79));
			panel.Add(lblTitulo, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, grdMenu);

			if (Platform.Current.Page.Width > 250)
			{
				IImage imgLogo = Platform.Current.Create<IImage>();
				imgLogo.LoadFromUrl(new Uri("http://radioudg.okhosting.com/images-old/icon2--14.png"));
				imgLogo.Width = Platform.Current.Page.Width / 6;
				imgLogo.Height = lblTitulo.Height;
				imgLogo.Margin = new Thickness(0, 0, 10, 0);
				panel.Add(imgLogo, RelativePanelHorizontalContraint.RightWith, RelativePanelVerticalContraint.TopWith, lblTitulo);
			}

			IImage imgAntena = Platform.Current.Create<IImage>();
			imgAntena.LoadFromUrl(new Uri("http://radioudg.okhosting.com/images-old/icon-22.png"));
			imgAntena.Width = Platform.Current.Page.Width * .1;
			imgAntena.Margin = new Thickness(10, 0, 10, 20);
			panel.Add(imgAntena, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, lblTitulo);

			ILabel lblAlAire = Platform.Current.Create<ILabel>();
			lblAlAire.Text = "Estas escuchando:";
			lblAlAire.Bold = true;
			lblAlAire.FontSize = Constantes.FontSize2;
			lblAlAire.FontFamily = Constantes.FontFamily;
			lblAlAire.FontColor = Constantes.FontColor2;
			panel.Add(lblAlAire, RelativePanelHorizontalContraint.RightWith, RelativePanelVerticalContraint.TopWith, imgAntena);

			var estacionDefault = RegionalesController.LeerEstaciones().First();

			AudioPlayer.Stop();
			AudioPlayer.Source = estacionDefault.StramingUri;

			IGrid grdReproductor = Platform.Current.Create<IGrid>();
			grdReproductor.RowCount = 1;
			grdReproductor.ColumnCount = 4;
			grdReproductor.Width = Platform.Current.Page.Width - 20;
			grdReproductor.BackgroundColor = new Color(60, 255, 255, 255);
			panel.Add(grdReproductor, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, imgAntena);

			imgLogoPrograma = Platform.Current.Create<IImage>();
			imgLogoPrograma.LoadFromUrl(estacionDefault.WebSiteUri);
			imgLogoPrograma.Width = Constantes.AnchoIconos;
			imgLogoPrograma.Height = Constantes.AnchoIconos;
			imgLogoPrograma.Margin = new Thickness(0, 0, 10, 0);

			panel.Add(imgLogoPrograma, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.TopWith, grdReproductor);

			lblNombre = Platform.Current.Create<ILabel>();
			lblNombre.Text = estacionDefault.Name;
			lblNombre.FontColor = Constantes.FontColor2;
			lblNombre.FontFamily = Constantes.FontFamily;
			lblNombre.FontSize = Constantes.FontSize2;
			lblNombre.Bold = true;
			lblNombre.Width = Platform.Current.Page.Width - (Constantes.AnchoIconos * 3) + 10;
			panel.Add(lblNombre, RelativePanelHorizontalContraint.RightOf, RelativePanelVerticalContraint.TopWith, imgLogoPrograma);

			lblDescripcion = Platform.Current.Create<ILabel>();
			lblDescripcion.Text = estacionDefault.Description;
			lblDescripcion.FontColor = Constantes.FontColor3;
			lblDescripcion.FontFamily = Constantes.FontFamily;
			lblDescripcion.FontSize = Constantes.FontSize3;
			lblDescripcion.Margin = new Thickness(0, 5, 0, 0);
			lblDescripcion.Width = lblNombre.Width;
			panel.Add(lblDescripcion, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, lblNombre);

			cmdPlay = Platform.Current.Create<IImageButton>();
			cmdPlay.LoadFromUrl(new Uri("http://radioudg.okhosting.com/images/app-54.png"));
			cmdPlay.Click += Play_Click;
			cmdPlay.Width = Constantes.AnchoIconos;
			cmdPlay.Height = Constantes.AnchoIconos;

			panel.Add(cmdPlay, RelativePanelHorizontalContraint.RightOf, RelativePanelVerticalContraint.TopWith, lblNombre);

			Platform.Current.Page.Title = "Radio Universidad de Guadalajara";
			Platform.Current.Page.Content = panel;

			Play_Click (null, null);
		}
Exemplo n.º 51
0
 protected abstract void ShowPlayerStatus(IAudioPlayer player, bool isPlaying);
Exemplo n.º 52
0
        static void Init()
        {
            LED = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED, false);

            var settings = Settings.Init(null);
            var log = settings.Log || settings.LogToSD;

            // TODO move to settings
            Localization.Current = new EnglishLocalization();
            Features.Comfort.AutoLockDoors = true;
            Features.Comfort.AutoUnlockDoors = true;
            Features.Comfort.AutoCloseWindows = true;
            Logger.Info("Preferences inited");

            Logger.Info(version);
            SettingsScreen.Instance.Status = version;

            // Create serial port to work with Melexis TH3122
            ISerialPort iBusPort = new SerialPortTH3122(Serial.COM3, (Cpu.Pin)FEZ_Pin.Interrupt.Di4);
            //ISerialPort iBusPort = new SerialPortOptoPair(Serial.COM3);
            Logger.Info("TH3122 serial port inited");

            InputPort jumper = new InputPort((Cpu.Pin)FEZ_Pin.Digital.An7, false, Port.ResistorMode.PullUp);
            /*if (!jumper.Read())
            {
                Logger.Info("Jumper installed. Starting virtual COM port");

                // Init hub between iBus port and virtual USB COM port
                ISerialPort cdc = new SerialPortCDC(USBClientController.StandardDevices.StartCDC_WithDebugging(), 0, iBus.Message.PacketLengthMax);
                iBusPort = new SerialPortHub(iBusPort, cdc);
                Logger.Info("Serial port hub started");
            }*/

            // Enable iBus Manager
            iBus.Manager.Init(iBusPort);
            Logger.Info("iBus manager inited");

            Message sent1 = null, sent2 = null; // light "buffer" for last 2 messages
            bool isSent1 = false;
            iBus.Manager.BeforeMessageReceived += (e) =>
            {
                LED.Write(Busy(true, 1));
            };
            iBus.Manager.AfterMessageReceived += (e) =>
            {
                LED.Write(Busy(false, 1));

                if (!log)
                {
                    return;
                }

                // Show only messages which are described
                if (e.Message.Describe() == null) { return; }
                // Filter CDC emulator messages echoed by iBus
                //if (e.Message.SourceDevice == iBus.DeviceAddress.CDChanger) { return; }
                if (e.Message.SourceDevice != DeviceAddress.Radio
                    && e.Message.DestinationDevice != DeviceAddress.Radio
                    && e.Message.SourceDevice != DeviceAddress.GraphicsNavigationDriver
                    && e.Message.SourceDevice != DeviceAddress.Diagnostic && e.Message.DestinationDevice != DeviceAddress.Diagnostic)
                {
                    return;
                }
                if (e.Message.ReceiverDescription == null)
                {
                    if (sent1 != null && sent1.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent1.ReceiverDescription;
                    }
                    else if (sent2 != null && sent2.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent2.ReceiverDescription;
                    }
                }
                if (settings.LogMessageToASCII)
                {
                    Logger.Info(e.Message.ToPrettyString(true, true), "< ");
                }
                else
                {
                    Logger.Info(e.Message, "< ");
                }
                /*if (e.Message.ReceiverDescription == null)
                {
                    Logger.Info(ASCIIEncoding.GetString(e.Message.Data));
                }*/
                //Logger.Info(e.Message.PacketDump);
            };
            iBus.Manager.BeforeMessageSent += (e) =>
            {
                LED.Write(Busy(true, 2));
            };
            iBus.Manager.AfterMessageSent += (e) =>
            {
                LED.Write(Busy(false, 2));

                if (!log)
                {
                    return;
                }

                Logger.Info(e.Message, " >");
                if (isSent1)
                {
                    sent1 = e.Message;
                }
                else
                {
                    sent2 = e.Message;
                }
                isSent1 = !isSent1;
            };
            Logger.Info("iBus manager events subscribed");

            // Set iPod or Bluetooth as AUX or CDC-emulator for Bordmonitor or Radio
            //player = new BluetoothOVC3860(Serial.COM2, sd != null ? sd + @"\contacts.vcf" : null);
            player = new iPodViaHeadset((Cpu.Pin)FEZ_Pin.Digital.Di3);

            MediaEmulator emulator;
            if (settings.MenuMode != Tools.MenuMode.RadioCDC || Manager.FindDevice(DeviceAddress.OnBoardMonitor))
            {
                if (settings.MenuMode == Tools.MenuMode.BordmonitorCDC)
                {
                    emulator = new CDChanger(player);
                    if (settings.NaviVersion == NaviVersion.MK2)
                    {
                        Localization.Current = new RadioLocalization();
                        SettingsScreen.Instance.CanChangeLanguage = false;
                    }
                }
                else
                {
                    emulator = new BordmonitorAUX(player);
                }
                Bordmonitor.NaviVersion = settings.NaviVersion;
                BordmonitorMenu.FastMenuDrawing = settings.NaviVersion == NaviVersion.MK4;
                //MenuScreen.MaxItemsCount = 6;
                BordmonitorMenu.Init(emulator);

                Logger.Info("Bordmonitor menu inited");
            }
            else
            {
                Localization.Current = new RadioLocalization();
                SettingsScreen.Instance.CanChangeLanguage = false;
                MultiFunctionSteeringWheel.EmulatePhone = true;
                Radio.HasMID = Manager.FindDevice(DeviceAddress.MultiInfoDisplay);
                var menu = RadioMenu.Init(new CDChanger(player));
                menu.TelephoneModeForNavigation = settings.MenuMFLControl;
                Logger.Info("Radio menu inited" + (Radio.HasMID ? " with MID" : ""));
            }

            LED.Write(true);
            Thread.Sleep(50);
            LED.Write(false);
            Logger.Info("LED blinked - inited");
        }
Exemplo n.º 53
0
        protected void ShowPlayerStatus(IAudioPlayer player, string status)
        {
            if (!IsEnabled)
            {
                //return;
                Logger.Warning("Why shouldn't I set player status when menu is disabled?!");
            }
            if (displayStatusDelayTimer != null)
            {
                displayStatusDelayTimer.Dispose();
                displayStatusDelayTimer = null;
            }

            player.Menu.Status = status;
        }
Exemplo n.º 54
0
 public PlayNextTrackCommand(IPlaylist playlist, IMessenger messenger, IAudioPlayer player)
     : base(playlist, messenger, player, p => p.NextTrack)
 {
 }
Exemplo n.º 55
0
 void mediaEmulator_PlayerChanged(IAudioPlayer player)
 {
     HomeScreen.Instance.PlayerScreen = player.Menu;
 }
Exemplo n.º 56
0
 public void RegisterAudioPlayer(IEnumerable<string> extensions, IAudioPlayer player)
 {
     _audioPlayers.Add(extensions, player);
 }
Exemplo n.º 57
0
 protected override void ShowPlayerStatus(IAudioPlayer player, bool isPlaying)
 {
     string s = isPlaying ? Localization.Current.Playing : Localization.Current.Paused;
     ShowPlayerStatus(player, s);
 }
Exemplo n.º 58
0
 protected override void ShowPlayerStatus(IAudioPlayer player, string status, PlayerEvent playerEvent)
 {
     if (!IsEnabled)
     {
         return;
     }
     bool showAfterWithDelay = false;
     switch (playerEvent)
     {
         case PlayerEvent.Next:
             status = Localization.Current.Next;
             showAfterWithDelay = true;
             break;
         case PlayerEvent.Prev:
             status = Localization.Current.Previous;
             showAfterWithDelay = true;
             break;
         case PlayerEvent.Playing:
             status = TextWithIcon(">", status);
             break;
         case PlayerEvent.Current:
             status = TextWithIcon("\x07", status);
             break;
         case PlayerEvent.Voice:
             status = TextWithIcon("*", status);
             break;
         case PlayerEvent.Settings:
             status = TextWithIcon("*", status);
             showAfterWithDelay = true;
             break;
     }
     ShowPlayerStatus(player, status);
     if (showAfterWithDelay)
     {
         ShowPlayerStatusWithDelay(player);
     }
 }
 public PlayPreviousTrackCommand(IPlaylist playlist, IMessenger messenger, IAudioPlayer player)
     : base(playlist, messenger, player, p => p.PreviousTrack)
 {
 }
Exemplo n.º 60
0
        static void Init()
        {
            LED = new OutputPort(Pin.LED, false);

            #region Settings

            var sd = GetRootDirectory();

            var settings = Settings.Init(sd != null ? sd + @"\imBMW.ini" : null);
            var log = settings.Log || settings.LogToSD;

            Localization.SetCurrent(settings.Language);
            Features.Comfort.AutoLockDoors = settings.AutoLockDoors;
            Features.Comfort.AutoUnlockDoors = settings.AutoUnlockDoors;
            Features.Comfort.AutoCloseWindows = settings.AutoCloseWindows;
            Features.Comfort.AutoCloseSunroof = settings.AutoCloseSunroof;
            Logger.Info("Preferences inited");

            #if DEBUG
            log = true;
            #else
            // already inited in debug mode
            if (settings.Log)
            {
                Logger.Logged += Logger_Logged;
                Logger.Info("Logger inited");
            }
            #endif

            if (settings.LogToSD && sd != null)
            {
                FileLogger.Init(sd + @"\Logs", () =>
                {
                    VolumeInfo.GetVolumes()[0].FlushAll();
                });
            }

            Logger.Info(version);
            SettingsScreen.Instance.Status = version.Length > 11 ? version.Replace(" ", "") : version;

            #endregion

            #region iBus Manager

            // Create serial port to work with Melexis TH3122
            //ISerialPort iBusPort = new SerialPortEcho();
            ISerialPort iBusPort = new SerialPortTH3122(Serial.COM3, Pin.TH3122SENSTA, true);
            Logger.Info("TH3122 serial port inited");

            /*InputPort jumper = new InputPort((Cpu.Pin)FEZ_Pin.Digital.An7, false, Port.ResistorMode.PullUp);
            if (!jumper.Read())
            {
                Logger.Info("Jumper installed. Starting virtual COM port");

                // Init hub between iBus port and virtual USB COM port
                ISerialPort cdc = new SerialPortCDC(USBClientController.StandardDevices.StartCDC_WithDebugging(), 0, iBus.Message.PacketLengthMax);
                iBusPort = new SerialPortHub(iBusPort, cdc);
                Logger.Info("Serial port hub started");
            }*/

            iBus.Manager.Init(iBusPort);
            Logger.Info("iBus manager inited");

            #endregion

            #region iBus IO logging

            Message sent1 = null, sent2 = null; // light "buffer" for last 2 messages
            bool isSent1 = false;
            iBus.Manager.BeforeMessageReceived += (e) =>
            {
                LED.Write(Busy(true, 1));
            };
            iBus.Manager.AfterMessageReceived += (e) =>
            {
                LED.Write(Busy(false, 1));

                if (!log)
                {
                    return;
                }

                // Show only messages which are described
                if (e.Message.Describe() == null) { return; }
                // Filter CDC emulator messages echoed by iBus
                //if (e.Message.SourceDevice == iBus.DeviceAddress.CDChanger) { return; }
                if (e.Message.SourceDevice != DeviceAddress.Radio
                    && e.Message.DestinationDevice != DeviceAddress.Radio
                    && e.Message.SourceDevice != DeviceAddress.GraphicsNavigationDriver
                    && e.Message.SourceDevice != DeviceAddress.Diagnostic && e.Message.DestinationDevice != DeviceAddress.Diagnostic)
                {
                    //return;
                }
                var logIco = "< ";
                if (e.Message.ReceiverDescription == null)
                {
                    if (sent1 != null && sent1.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent1.ReceiverDescription;
                        logIco = "<E";
                    }
                    else if (sent2 != null && sent2.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent2.ReceiverDescription;
                        logIco = "<E";
                    }
                }
                if (settings.LogMessageToASCII)
                {
                    Logger.Info(e.Message.ToPrettyString(true, true), logIco);
                }
                else
                {
                    Logger.Info(e.Message, logIco);
                }
                /*if (e.Message.ReceiverDescription == null)
                {
                    Logger.Info(ASCIIEncoding.GetString(e.Message.Data));
                }*/
                //Logger.Info(e.Message.PacketDump);
            };
            iBus.Manager.BeforeMessageSent += (e) =>
            {
                LED.Write(Busy(true, 2));
            };
            iBus.Manager.AfterMessageSent += (e) =>
            {
                LED.Write(Busy(false, 2));

                if (!log)
                {
                    return;
                }

                Logger.Info(e.Message, " >");
                if (isSent1)
                {
                    sent1 = e.Message;
                }
                else
                {
                    sent2 = e.Message;
                }
                isSent1 = !isSent1;
            };
            Logger.Info("iBus manager events subscribed");

            #endregion

            #region Set iPod or Bluetooth as AUX or CDC-emulator for Bordmonitor or Radio

            //
            //Bordmonitor.ReplyToScreenUpdates = true;
            //settings.MenuMode = MenuMode.RadioCDC;
            //settings.MediaShield = "WT32";
            //settings.BluetoothPin = "1111";
            //

            BluetoothWT32 wt32;
            if (settings.MediaShield == "WT32")
            {
                wt32 = new BluetoothWT32(Serial.COM2, Settings.Instance.BluetoothPin);
                player = wt32;
                InternalCommunications.Register(wt32);

                byte gain = 0;
                Button.OnPress(Pin.Di14, () => wt32.SetMicGain((byte)(++gain % 16)));
            }
            else
            {
                player = new BluetoothOVC3860(Serial.COM2, sd != null ? sd + @"\contacts.vcf" : null);
                //player = new iPodViaHeadset(Pin.PC2);
            }

            //
            //player.IsCurrentPlayer = true;
            //player.PlayerHostState = PlayerHostState.On;
            //

            MediaEmulator emulator;
            if (settings.MenuMode != Tools.MenuMode.RadioCDC || Manager.FindDevice(DeviceAddress.OnBoardMonitor))
            {
                if (player is BluetoothWT32)
                {
                    ((BluetoothWT32)player).NowPlayingTagsSeparatedRows = true;
                }
                if (settings.MenuMode == Tools.MenuMode.BordmonitorCDC)
                {
                    emulator = new CDChanger(player);
                    if (settings.NaviVersion == NaviVersion.MK2)
                    {
                        Localization.Current = new RadioLocalization();
                        SettingsScreen.Instance.CanChangeLanguage = false;
                    }
                }
                else
                {
                    emulator = new BordmonitorAUX(player);
                }
                Bordmonitor.NaviVersion = settings.NaviVersion;
                BordmonitorMenu.FastMenuDrawing = settings.NaviVersion == NaviVersion.MK4;
                //MenuScreen.MaxItemsCount = 6;
                BordmonitorMenu.Init(emulator);

                Logger.Info("Bordmonitor menu inited");
            }
            else
            {
                Localization.Current = new RadioLocalization();
                SettingsScreen.Instance.CanChangeLanguage = false;
                MultiFunctionSteeringWheel.EmulatePhone = true;
                Radio.HasMID = Manager.FindDevice(DeviceAddress.MultiInfoDisplay);
                var menu = RadioMenu.Init(new CDChanger(player));
                menu.TelephoneModeForNavigation = settings.MenuMFLControl;
                Logger.Info("Radio menu inited" + (Radio.HasMID ? " with MID" : ""));
            }

            ShieldLED = new OutputPort(Pin.Di10, false);
            player.IsPlayingChanged += (p, s) =>
            {
                ShieldLED.Write(s);
                RefreshLEDs();
            };
            player.StatusChanged += (p, s, e) =>
            {
                if (e == PlayerEvent.IncomingCall && !p.IsEnabled)
                {
                    InstrumentClusterElectronics.Gong1();
                }
            };
            Logger.Info("Player events subscribed");

            #endregion

            /*blinkerTimer = new Timer((s) =>
            {
                if (InstrumentClusterElectronics.CurrentIgnitionState == IgnitionState.Off && !blinkerOn)
                {
                    return;
                }
                blinkerOn = !blinkerOn;
                RefreshLEDs();
            }, null, 0, 3000);*/

            RefreshLEDs();

            //
            //var ign = new Message(DeviceAddress.InstrumentClusterElectronics, DeviceAddress.GlobalBroadcastAddress, "Ignition ACC", 0x11, 0x01);
            //Manager.EnqueueMessage(ign);
            //Manager.AddMessageReceiverForDestinationDevice(DeviceAddress.InstrumentClusterElectronics, m =>
            //{
            //    if (m.Data.Compare(0x10))
            //    {
            //        Manager.EnqueueMessage(ign);
            //    }
            //});
            //var b = Manager.FindDevice(DeviceAddress.Radio);
            //

            LED.Write(true);
            Thread.Sleep(50);
            LED.Write(false);
            Logger.Info("LED blinked - inited");
        }