public MediaMetadataViewModel( MediaMetadata metadata, ReadOnlyObservableCollection <string> allTags, ReadOnlyObservableCollection <string> allCharacterTags, ReadOnlyObservableCollection <string> allCharacterNames) { _metadata = metadata; ((INotifyCollectionChanged)_metadata.Tags).CollectionChanged += TagsChanged; Tags = new MvxObservableCollection <MediaTagViewModel>(); foreach (MediaTag tag in _metadata.Tags) { Tags.Add(new MediaTagViewModel(tag, TagDeleted)); } ((INotifyCollectionChanged)_metadata.Characters).CollectionChanged += CharactersChanged; Characters = new MvxObservableCollection <MediaCharacterViewModel>(); foreach (MediaCharacter character in _metadata.Characters) { Characters.Add(new MediaCharacterViewModel(character, CharacterDeleted, allCharacterTags)); } AllTags = allTags; _allCharacterTags = allCharacterTags; AllCharacterNames = allCharacterNames; NewTag = string.Empty; NewCharacterName = string.Empty; }
public override WebImage OnPickImage(MediaMetadata mediaMetadata, ImageHints hints) { var type = hints.Type; if ((mediaMetadata == null) || !mediaMetadata.HasImages) { return(null); } var images = mediaMetadata.Images; if (images.Count == 1) { return(images[0]); } else { if (type == ImagePicker.ImageTypeMediaRouteControllerDialogBackground) { return(images[0]); } else { return(images[1]); } } }
public void Play(MediaSession.QueueItem item) { var mediaHasChanged = InitPlayerStates(item.Description.MediaId); if (MusicPlayerState == PlaybackStateCode.Paused && !mediaHasChanged && _mediaPlayer != null) { ConfigMediaPlayerState(); } else { MusicPlayerState = PlaybackStateCode.Stopped; CleanUp(false); MediaMetadata track = _musicProvider.GetMusic( HierarchyHelper.ExtractMusicIDFromMediaID(item.Description.MediaId)); string source = track.GetString(MusicProvider.PodcastSource); try { _mediaPlayer.Reset(); MusicPlayerState = PlaybackStateCode.Buffering; _mediaPlayer.SetAudioStreamType(Android.Media.Stream.Music); _mediaPlayer.SetDataSource(source); _mediaPlayer.PrepareAsync(); _wifiLock.Acquire(); _musicService.OnPlaybackStatusChanged(MusicPlayerState); } catch (Exception ex) { Logger.Error(ex, "Error playing song"); _musicService.OnError(ex.Message); } } }
/// <summary> /// Gets the duration, in ticks, of the currently playing content /// </summary> public static long GetDurationOfCurrentlyPlayingMedia(MediaMetadata metadata) { if (metadata != null) { string duration = string.Empty; if (metadata.ContainsKey("Duration")) { duration = metadata["Duration"] as string; } if (string.IsNullOrEmpty(duration) && metadata.ContainsKey("TrackDuration")) { duration = metadata["TrackDuration"] as string; // Found it in metadata, now parse if (!string.IsNullOrEmpty(duration)) { return(TimeSpan.FromSeconds(double.Parse(duration)).Ticks); } } // Found it in metadata, now parse if (!string.IsNullOrEmpty(duration)) { return(TimeSpan.Parse(duration).Ticks); } } return(0); }
public async Task <IActionResult> UploadFile(IFormFile file) { if (file == null || file.Length == 0) { return(BadRequest("file not selected")); } try { var url = await _mediaStorage.AddToStorage(file); var newMedia = new MediaMetadata { MediaUrl = url, MediaExtension = Path.GetExtension(file.FileName), FileName = file.FileName, }; await _context.MediaMetadata.AddAsync(newMedia); await _context.SaveChangesAsync(); } catch (Exception e) { return(BadRequest(e.Message)); } return(RedirectToAction("index")); }
public static void Run( [QueueTrigger(QueueNames.MediaToEncode)] MediaMetadata mediaMetadataFromQueue, [Queue(QueueNames.MediaToPublish)] out MediaMetadata mediaMetadataToPublish, TraceWriter log) { log.Info($"{nameof(EncodeMediaAsset)} triggered"); IAsset asset = null; try { asset = AzureMediaServices.GetAsset(mediaMetadataFromQueue); var newAsset = AzureMediaServices.EncodeToAdaptiveBitrateMP4Set(asset, mediaMetadataFromQueue.Title); mediaMetadataToPublish = new MediaMetadata { FileName = newAsset.Name, MediaServicesAssetId = newAsset.Id, MediaAssetUri = newAsset.Uri, Title = mediaMetadataFromQueue.Title, UploadedAt = mediaMetadataFromQueue.UploadedAt, }; } catch (Exception e) { log.Info($"Error {e.Message}"); throw e; } finally { asset?.Delete(false); log.Info($"{nameof(EncodeMediaAsset)} completed"); } }
public static List <MediaMetadata> GetAllItemInfos(string topFolder) { List <MediaMetadata> result = new List <MediaMetadata>(); DirectoryInfo mmFolder = new DirectoryInfo(topFolder); List <MyItem> myItems = new List <MyItem>(); foreach (var dirInfo in mmFolder.GetDirectories().OrderByDescending(t => t.CreationTimeUtc)) { var mediaFile = dirInfo.GetFiles() .FirstOrDefault(t => t.Extension.Equals(".mp4", StringComparison.OrdinalIgnoreCase)); var infoFile = dirInfo.GetFiles() .FirstOrDefault(t => t.Extension.Equals(".json", StringComparison.OrdinalIgnoreCase)); if (mediaFile == null || mediaFile.Exists == false || infoFile == null || infoFile.Exists == false) { continue; } MediaMetadata itemInfo = null; try { itemInfo = JsonConvert.DeserializeObject <MediaMetadata>(System.IO.File.ReadAllText(infoFile.FullName)); if (itemInfo != null) { itemInfo.id = MyItem.GetIdFromUrl(dirInfo.Name + "/" + mediaFile.Name); result.Add(itemInfo); } } catch { } } return(result); }
void CastVideo(object sender, EventArgs e) { // Show Alert if not connected if (DeviceManager == null || !DeviceManager.IsConnected) { new UIAlertView("Not Connected", "Please connect to a cast device", null, "Ok", null).Show(); return; } // Define Media metadata var metadata = new MediaMetadata(); metadata.SetString("Big Buck Bunny (2008)", MetadataKey.Title); metadata.SetString("Big Buck Bunny tells the story of a giant rabbit with a heart bigger than " + "himself. When one sunny day three rodents rudely harass him, something " + "snaps... and the rabbit ain't no bunny anymore! In the typical cartoon " + "tradition he prepares the nasty rodents a comical revenge.", MetadataKey.Subtitle); metadata.AddImage(new Image(new NSUrl("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg"), 480, 360)); // define Media information var mediaInformation = new MediaInformation("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", MediaStreamType.None, "video/mp4", metadata, 0, null); // cast video MediaControlChannel.LoadMedia(mediaInformation, true, 0); }
public static void CreateDefaultItemMetadata(string pageId, string itemName, ref MediaMetadata metadata) { string itemPath = GetItemFullPath(pageId, itemName); if (string.IsNullOrEmpty(itemPath)) { throw new Exception(string.Format("{0} not found.", itemPath)); } string fileName = Path.Combine(itemPath, itemName + ".json"); var metadataFileInfo = new FileInfo(fileName); if (metadataFileInfo.Exists) { throw new Exception(string.Format("{0} was exists. it's fail to set default.", itemPath)); } metadata = new MediaMetadata { id = itemName, title = string.Empty, like = 0, category = string.Empty, cover = string.Empty, hidden = 0, uncensored = 0 }; string jsonText = JsonConvert.SerializeObject(metadata, Formatting.Indented); File.WriteAllText(metadataFileInfo.FullName, jsonText); }
/// <summary> /// Gets the title of the currently playing content /// </summary> public static string GetTitleOfCurrentlyPlayingMedia(MediaMetadata metadata) { if (metadata == null) { return(string.Empty); } string title = string.Empty; // Changed this to get the "Name" property instead. That makes it compatable with DVD playback as well. if (metadata.ContainsKey("Name")) { title = metadata["Name"] as string; } if (string.IsNullOrEmpty(title) || title.ToLower().EndsWith(".wpl")) { if (metadata.ContainsKey("Title")) { title = metadata["Title"] as string; } else if (metadata.ContainsKey("Uri")) { // Use this for audio. Will get the path to the audio file even in the context of a playlist // But with video this will return the wpl file title = metadata["Uri"] as string; } } return(string.IsNullOrEmpty(title) ? string.Empty : title); }
public void GenerateDash_MidLevelApiOptions_ProducesCorrectDashEncodeResult() { Encoder encoder = new Encoder(ffmpegPath, ffprobePath, mp4boxPath, ffmpegCommandGenerator: (dashConfig, mediaMetadata) => { DashConfig c = dashConfig; MediaMetadata m = mediaMetadata; FFmpegCommand r = Encoder.GenerateFFmpegCommand(c, m); return(r); }, mp4BoxCommandGenerator: (dashConfig, videoStreams, audioStreams) => { DashConfig c = dashConfig; IEnumerable <VideoStreamCommand> v = videoStreams; IEnumerable <AudioStreamCommand> a = audioStreams; Mp4BoxCommand r = Encoder.GenerateMp4BoxCommand(c, v, a); return(r); }); DashConfig config = new DashConfig(testFileName, RunPath, Qualities, "output"); encodeResult = encoder.GenerateDash(config, encoder.ProbeFile(config.InputFilePath, out _)); Assert.NotNull(encodeResult.DashFilePath); Assert.NotNull(encodeResult.DashFileContent); Assert.NotNull(encodeResult.MediaFiles); Assert.Equal(4, encodeResult.MediaFiles.Count()); }
void UpdateMetadata() { if (!QueueHelper.isIndexPlayable(currentIndexOnQueue, playingQueue)) { LogHelper.Error(Tag, "Can't retrieve current metadata."); UpdatePlaybackState(Resources.GetString(Resource.String.error_no_metadata)); return; } MediaSession.QueueItem queueItem = playingQueue [currentIndexOnQueue]; string musicId = MediaIDHelper.ExtractMusicIDFromMediaID( queueItem.Description.MediaId); MediaMetadata track = musicProvider.GetMusic(musicId); string trackId = track.GetString(MediaMetadata.MetadataKeyMediaId); if (musicId != trackId) { var e = new InvalidOperationException("track ID should match musicId."); LogHelper.Error(Tag, "track ID should match musicId.", " musicId=", musicId, " trackId=", trackId, " mediaId from queueItem=", queueItem.Description.MediaId, " title from queueItem=", queueItem.Description.Title, " mediaId from track=", track.Description.MediaId, " title from track=", track.Description.Title, " source.hashcode from track=", track.GetString( MusicProvider.CustomMetadataTrackSource).GetHashCode(), e); throw e; } LogHelper.Debug(Tag, "Updating metadata for MusicID= " + musicId); session.SetMetadata(track); // Set the proper album artwork on the media session, so it can be shown in the // locked screen and in other places. if (track.Description.IconBitmap == null && track.Description.IconUri != null) { string albumUri = track.Description.IconUri.ToString(); AlbumArtCache.Instance.Fetch(albumUri, new AlbumArtCache.FetchListener { OnFetched = (artUrl, bitmap, icon) => { MediaSession.QueueItem qItem = playingQueue [currentIndexOnQueue]; MediaMetadata trackItem = musicProvider.GetMusic(trackId); trackItem = new MediaMetadata.Builder(trackItem) .PutBitmap(MediaMetadata.MetadataKeyAlbumArt, bitmap) .PutBitmap(MediaMetadata.MetadataKeyDisplayIcon, icon) .Build(); musicProvider.UpdateMusic(trackId, trackItem); // If we are still playing the same music string currentPlayingId = MediaIDHelper.ExtractMusicIDFromMediaID( qItem.Description.MediaId); if (trackId == currentPlayingId) { session.SetMetadata(trackItem); } } }); } }
// Builds all the information to be sent to Cast device. MediaInformation BuildMediaInformation(int categoryIndexSelected, int videoIndexSelected) { var category = categories [categoryIndexSelected]; var video = category.Videos [videoIndexSelected]; var metadata = new MediaMetadata(MediaMetadataType.Movie); metadata.SetString(video.Title, MetadataKey.Title); metadata.SetString(video.Subtitle, MetadataKey.Subtitle); metadata.SetString(video.Studio, MetadataKey.Studio); var imageUrl = new NSUrl($"{category.ImagesBaseUrl}{video.ImageUrl}"); metadata.AddImage(new Image(imageUrl, 480, 720)); var posterUrl = new NSUrl($"{category.ImagesBaseUrl}{video.PosterUrl}"); metadata.AddImage(new Image(posterUrl, 780, 1200)); string videoUrl = string.Empty; var tracks = new List <MediaTrack> (); video.Tracks = video.Tracks ?? new List <Track> (); foreach (var track in video.Tracks) { tracks.Add(new MediaTrack( int.Parse(track.Id), $"{category.TracksBaseUrl}{track.ContentId}", track.Type, MediaTrackType.Text, MediaTextTrackSubtype.Captions, track.Name, track.Language, null)); } foreach (var source in video.Sources) { if (!source.Type.Equals("mp4")) { continue; } videoUrl = $"{category.Mp4BaseUrl}{source.Url}"; } var mediaInformation = new MediaInformation(videoUrl, MediaStreamType.Buffered, "video/mp4", metadata, video.Duration, tracks.ToArray(), null, null); return(mediaInformation); }
private void ScanFile(ref UploadedMedia uploadedMedia, ref MediaMetadata mediaMetadata) { var scanResults = this._mediaMalwareVerificationService.Validate(uploadedMedia.Stream, uploadedMedia.FileName, uploadedMedia.ContentType); mediaMetadata.LatestScanDateTimeUtc = this._universalDateTimeService.NowUtc().UtcDateTime; mediaMetadata.LatestScanResults = scanResults.LatestScanResults; mediaMetadata.LatestScanMalwareDetetected = scanResults.LatestScanMalwareDetected; }
public MediaNotificationManager(MusicService serv) { service = serv; UpdateSessionToken(); notificationColor = ResourceHelper.GetThemeColor(service, Android.Resource.Attribute.ColorPrimary, Color.DarkGray); notificationManager = (NotificationManager)service .GetSystemService(Context.NotificationService); string pkg = service.PackageName; pauseIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionPause).SetPackage(pkg), PendingIntentFlags.CancelCurrent); playIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionPlay).SetPackage(pkg), PendingIntentFlags.CancelCurrent); previousIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionPrev).SetPackage(pkg), PendingIntentFlags.CancelCurrent); nextIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionNext).SetPackage(pkg), PendingIntentFlags.CancelCurrent); notificationManager.CancelAll(); mCb.OnPlaybackStateChangedImpl = (state) => { playbackState = state; LogHelper.Debug(Tag, "Received new playback state", state); if (state != null && (state.State == PlaybackStateCode.Stopped || state.State == PlaybackStateCode.None)) { StopNotification(); } else { Notification notification = CreateNotification(); if (notification != null) { notificationManager.Notify(NotificationId, notification); } } }; mCb.OnMetadataChangedImpl = (meta) => { metadata = meta; LogHelper.Debug(Tag, "Received new metadata ", metadata); Notification notification = CreateNotification(); if (notification != null) { notificationManager.Notify(NotificationId, notification); } }; mCb.OnSessionDestroyedImpl = () => { LogHelper.Debug(Tag, "Session was destroyed, resetting to the new session token"); UpdateSessionToken(); }; }
public override void OnSessionDestroyed() { Jukebox.MediaEvent -= Jukebox_MediaEvent; PlaybackState?.Dispose(); TransportControls?.Dispose(); MediaMetadata?.Dispose(); instance = null; Log.Info("LiveDisplay", "MusicController dispose method"); base.OnSessionDestroyed(); }
public Android.Gms.Cast.MediaInfo CreateMediaInfo() { MediaMetadata metadata = new MediaMetadata(MediaMetadata.MediaTypeMovie); metadata.PutString(MediaMetadata.KeySubtitle, "Hello World Fridays!"); metadata.PutString(MediaMetadata.KeyTitle, mediaInfo.DisplayName); var castableMedia = new Android.Gms.Cast.MediaInfo.Builder(mediaInfo.SourceURL).SetMetadata(metadata).Build(); return(castableMedia); }
private static MediaQueueItem buildMediaQueueItem(DemoUtil.Sample sample) { MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MediaTypeMovie); movieMetadata.PutString(MediaMetadata.KeyTitle, sample.name); MediaInfo mediaInfo = new MediaInfo.Builder(sample.uri) .SetStreamType(MediaInfo.StreamTypeBuffered).SetContentType(sample.mimeType) .SetMetadata(movieMetadata).Build(); return(new MediaQueueItem.Builder(mediaInfo).Build()); }
private string GetMetaString(MediaMetadata MediaMetadata, string Key) { string retStr = ""; object objStr = ""; MediaMetadata.TryGetValue(Key, out objStr); if (!string.IsNullOrEmpty((string)objStr)) { retStr = (string)objStr; } return(retStr); }
public void Play(MediaSession.QueueItem item) { playOnFocusGain = true; TryToGetAudioFocus(); RegisterAudioNoisyReceiver(); string mediaId = item.Description.MediaId; bool mediaHasChanged = mediaId != currentMediaId; if (mediaHasChanged) { currentPosition = 0; currentMediaId = mediaId; } if (State == PlaybackStateCode.Paused && !mediaHasChanged && mediaPlayer != null) { ConfigMediaPlayerState(); } else { State = PlaybackStateCode.Stopped; RelaxResources(false); MediaMetadata track = musicProvider.GetMusic( MediaIDHelper.ExtractMusicIDFromMediaID(item.Description.MediaId)); string source = track.GetString(MusicProvider.CustomMetadataTrackSource); try { CreateMediaPlayerIfNeeded(); State = PlaybackStateCode.Buffering; mediaPlayer.SetAudioStreamType(Android.Media.Stream.Music); mediaPlayer.SetDataSource(source); mediaPlayer.PrepareAsync(); wifiLock.Acquire(); if (Callback != null) { Callback.OnPlaybackStatusChanged(State); } } catch (IOException ex) { LogHelper.Error(Tag, ex, "Exception playing song"); if (Callback != null) { Callback.OnError(ex.Message); } } } }
public async Task GetMetadata() { // Arrange Mock <IGeoDecoderService> mock = CreateGeoDecoderMock(); Stream image = TestMediaLibrary.WithExif; var metadataExtractor = new MetadataExtractor(mock.Object); // Act MediaMetadata meta = await metadataExtractor.GetMetadataAsync(image, default); // Assert meta.MatchSnapshot(); }
public void UpdateMusic (string musicId, MediaMetadata metadata) { var track = musicListById [musicId]; if (track == null) return; var oldGenre = track.Metadata.GetString (MediaMetadata.MetadataKeyGenre); var newGenre = metadata.GetString (MediaMetadata.MetadataKeyGenre); track.Metadata = metadata; if (oldGenre != newGenre) BuildListsByGenre (); }
public MediaNotificationManager(MusicService serv) { service = serv; UpdateSessionToken(); notificationColor = ResourceHelper.GetThemeColor(service, Android.Resource.Attribute.ColorPrimary, Color.DarkGray); notificationManager = (NotificationManager) service .GetSystemService(Context.NotificationService); string pkg = service.PackageName; pauseIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionPause).SetPackage(pkg), PendingIntentFlags.CancelCurrent); playIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionPlay).SetPackage(pkg), PendingIntentFlags.CancelCurrent); previousIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionPrev).SetPackage(pkg), PendingIntentFlags.CancelCurrent); nextIntent = PendingIntent.GetBroadcast(service, RequestCode, new Intent(ActionNext).SetPackage(pkg), PendingIntentFlags.CancelCurrent); notificationManager.CancelAll (); mCb.OnPlaybackStateChangedImpl = (state) => { playbackState = state; LogHelper.Debug (Tag, "Received new playback state", state); if (state != null && (state.State == PlaybackStateCode.Stopped || state.State == PlaybackStateCode.None)) { StopNotification (); } else { Notification notification = CreateNotification (); if (notification != null) { notificationManager.Notify (NotificationId, notification); } } }; mCb.OnMetadataChangedImpl = (meta) => { metadata = meta; LogHelper.Debug (Tag, "Received new metadata ", metadata); Notification notification = CreateNotification (); if (notification != null) { notificationManager.Notify (NotificationId, notification); } }; mCb.OnSessionDestroyedImpl = () => { LogHelper.Debug (Tag, "Session was destroyed, resetting to the new session token"); UpdateSessionToken (); }; }
//Service to create a metadata object that describes the uploaded Media file. public MediaMetadata Create(UploadedMedia uploadedMedia, NZDataClassification dataClassification) { var result = new MediaMetadata(); result.ContentSize = uploadedMedia.Length; result.SourceFileName = uploadedMedia.FileName; result.DataClassificationFK = dataClassification; result.ContentHash = uploadedMedia.Stream.GetHashAsString(this._metadataServiceConfiguration.MediaManagementConfiguration.HashType); result.MimeType = uploadedMedia.ContentType ?? "Unknown"; result.UploadedDateTimeUtc = this._universalDateTimeService.NowUtc().UtcDateTime; return(result); }
private static void TestSerializationAndDeserialization(MediaMetadata originalObject) { using (var memoryStream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, originalObject); memoryStream.Seek(0, SeekOrigin.Begin); var deserializedObject = (MediaMetadata)formatter.Deserialize(memoryStream); Assert.AreEqual<MediaMetadata>(originalObject, deserializedObject); } }
public static void SaveItemMetadata(string pageId, string itemName, MediaMetadata metadata) { string itemPath = GetItemFullPath(pageId, itemName); if (string.IsNullOrEmpty(itemPath)) { throw new Exception(string.Format("{0} not found.", itemPath)); } string fileName = Path.Combine(itemPath, itemName + ".json"); var metadataFileInfo = new FileInfo(fileName); string jsonText = JsonConvert.SerializeObject(metadata, Formatting.Indented); File.WriteAllText(metadataFileInfo.FullName, jsonText); }
public override void OnMetadataChanged(MediaMetadata metadata) { MediaMetadata = metadata; OnMediaMetadataChanged(new MediaMetadataChangedEventArgs { ActivityIntent = ActivityIntent, MediaMetadata = metadata }); //Datos de la Media que se está reproduciendo. base.OnMetadataChanged(metadata); //Memory is growing until making a GC. GC.Collect(); }
public static void AddMediaMetadata(VideoDetails videoDetails, string mediaType, string quality, long size) { var newEntity = new MediaMetadata() { YID = videoDetails.id, Title = videoDetails.Title, DateStamp = DateTime.UtcNow, ThumbUrl = videoDetails.thumbnails.MediumResUrl, MediaType = mediaType, Quality = quality, Size = size }; DBContext.Current.Save(newEntity); }
private static void LoadMediaControllerData(MediaController controller) { if (controller != null) { _transportControls = controller.GetTransportControls(); _mediaMetadata = controller.Metadata; _playbackState = controller.PlaybackState; _activityIntent = controller.SessionActivity; _appname = PackageUtils.GetTheAppName(controller.PackageName); //Invoke MediaMetadata and MediaPlayback changed events, so all listeners will get notified of //the new Loaded mediacontroller. instance?.OnMetadataChanged(controller.Metadata); instance?.OnPlaybackStateChanged(controller.PlaybackState); } }
public async Task ImportMedia() { Stream image = TestMediaLibrary.TwoFacesWithExif; MediaMetadata meta = await _metadataExtractor.GetMetadataAsync(image, default); image.Position = 0; IEnumerable <FaceData> dataData = await GetFaceData(image); image.Position = 0; IEnumerable <ThumbnailResult> thums = await _thumbnailService .GenerateAllThumbnailAsync(image, default); var media = new Media { Id = Guid.NewGuid(), MediaType = MediaType.Image, DateTaken = meta.DateTaken, GeoLocation = meta.GeoLocation, Size = image.Length }; media.Thumbnails = thums.Select(x => new MediaThumbnail { Id = Guid.NewGuid(), Data = x.Data, Format = x.Format, Dimensions = x.Dimensions, Size = x.Size }); IEnumerable <MediaFace> faces = dataData.Select(f => new MediaFace { Box = f.Box, Id = f.Id, Encoding = f.Encoding, MediaId = media.Id, RecognitionType = FaceRecognitionType.None, State = FaceState.New, Thumbnail = f.Thumbnail, }); media.FaceCount = faces.Count(); await _store.InsertMediaAsync(media, faces, default); }
private void SetCustomAction(PlaybackState.Builder stateBuilder) { MediaMetadata currentMusic = GetCurrentPlayingMusic(); if (currentMusic != null) { // Set appropriate "Favorite" icon on Custom action: var musicId = currentMusic.GetString(MediaMetadata.MetadataKeyMediaId); var favoriteIcon = Resource.Drawable.ic_star_off; if (_musicProvider.IsFavorite(musicId)) { favoriteIcon = Resource.Drawable.ic_star_on; } stateBuilder.AddCustomAction(CustomActionFavorite, "Favorite", favoriteIcon); } }
private static MediaMetadata ParseUrls(string content, ILogger logger) { MediaMetadata metadata = new MediaMetadata(); //this should be a url nfo, so just check for url links string[] lines = content.Split( new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None ); foreach (var line in lines) { try { UriBuilder uriBuilder = new UriBuilder(line); var domainParser = new DomainParser(new WebTldRuleProvider()); var domainName = domainParser.Get(uriBuilder.Host); Identifier id = new Identifier(); switch (domainName.Domain) { case "themoviedb": id.Type = "tmdb"; break; default: id.Type = domainName.Domain; break; } id.Url = uriBuilder.Uri.AbsoluteUri; if (id.Url.EndsWith("/")) { id.Url = id.Url.Substring(0, id.Url.Length - 1); } id.Id = UrlParser.GetMediaId(uriBuilder.Uri); metadata.Identifiers.Add(id); } catch (UriFormatException) { logger.LogError($"Line not url: {line}"); } } return(metadata); }
public override void OnMetadataChanged(MediaMetadata metadata) { _mediaMetadata = metadata; OnMediaMetadataChanged(new MediaMetadataChangedEventArgs { ActivityIntent = _activityIntent, MediaMetadata = _mediaMetadata, AppName = _appname, OpenNotificationId = _openNotificationId }); //Datos de la Media que se está reproduciendo. base.OnMetadataChanged(_mediaMetadata); //Memory is growing until making a GC. GC.Collect(); }
public override void OnMetadataChanged(MediaMetadata meta) { OnMetadataChangedImpl (meta); }
/// <summary> /// Gets the duration, in ticks, of the currently playing content /// </summary> public static long GetDurationOfCurrentlyPlayingMedia(MediaMetadata metadata) { if (metadata != null) { string duration = string.Empty; if (metadata.ContainsKey("Duration")) { duration = metadata["Duration"] as string; } if (string.IsNullOrEmpty(duration) && metadata.ContainsKey("TrackDuration")) { duration = metadata["TrackDuration"] as string; // Found it in metadata, now parse if (!string.IsNullOrEmpty(duration)) { return TimeSpan.FromSeconds(double.Parse(duration)).Ticks; } } // Found it in metadata, now parse if (!string.IsNullOrEmpty(duration)) { return TimeSpan.Parse(duration).Ticks; } } return 0; }
public void SetSongUri() { string songUri = "http://freemusicarchive.org/music/download/4cc908b1d8b19b9bdfeb87f9f9fd5086b66258b8"; if (googleApiClient != null && mediaPlayer != null) { try { //currentSongInfo = info; var metadata = new MediaMetadata(MediaMetadata.MediaTypeMusicTrack); metadata.PutString(MediaMetadata.KeyArtist, "Deadlines"); metadata.PutString(MediaMetadata.KeyAlbumTitle, "Magical Inertia"); metadata.PutString(MediaMetadata.KeyTitle, "The Wire"); var androidUri = Android.Net.Uri.Parse("http://freemusicarchive.org/file/images/albums/Deadlines_-_Magical_Inertia_-_20150407163159222.jpg?width=290&height=290"); var webImage = new Android.Gms.Common.Images.WebImage(androidUri); metadata.AddImage(webImage); MediaInfo mediaInfo = new MediaInfo.Builder(songUri).SetContentType("audio/mp3") .SetMetadata(metadata) .SetStreamType(MediaInfo.StreamTypeBuffered) .Build(); mediaPlayer.Load(googleApiClient, mediaInfo, true, 0) .SetResultCallback<RemoteMediaPlayer.IMediaChannelResult> (r => { Console.WriteLine ("Loaded"); }); } catch (Exception e) { Console.WriteLine ("Exception while sending a song. Exception : " + e.Message); } } }
void SimpleCastBtn_TouchUpInside(object sender, EventArgs e) { //Show Alert if not connected if (DeviceManager == null || DeviceManager.ConnectionState != ConnectionState.Connected) { new UIAlertView ("Not Connected", "Please connect to a cast device", null, "Ok", null).Show (); return; } // Define Media metadata var metadata = new MediaMetadata (); metadata.SetString ("Big Buck Bunny (2008)", MetadataKey.Title); metadata.SetString ("Big Buck Bunny tells the story of a giant rabbit with a heart bigger than " + "himself. When one sunny day three rodents rudely harass him, something " + "snaps... and the rabbit ain't no bunny anymore! In the typical cartoon " + "tradition he prepares the nasty rodents a comical revenge.", MetadataKey.Subtitle); metadata.AddImage (new Image (new NSUrl ("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg"), 480, 360)); // define Media information var mediaInformation = new MediaInformation ("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", MediaStreamType.None, "video/mp4", metadata, 0, null); // cast video MediaControlChannel.LoadMedia (mediaInformation, true, 0); }
public void StartNotification() { if (!started) { metadata = controller.Metadata; playbackState = controller.PlaybackState; // The notification must be updated after setting started to true Notification notification = CreateNotification (); if (notification != null) { controller.RegisterCallback (mCb); var filter = new IntentFilter (); filter.AddAction (ActionNext); filter.AddAction (ActionPause); filter.AddAction (ActionPlay); filter.AddAction (ActionPrev); service.RegisterReceiver (this, filter); service.StartForeground (NotificationId, notification); started = true; } } }
/// <summary> /// Gets the title of the currently playing content /// </summary> public static string GetTitleOfCurrentlyPlayingMedia(MediaMetadata metadata) { if (metadata == null) return string.Empty; string title = string.Empty; // Changed this to get the "Name" property instead. That makes it compatable with DVD playback as well. if (metadata.ContainsKey("Name")) { title = metadata["Name"] as string; } if (string.IsNullOrEmpty(title) || title.ToLower().EndsWith(".wpl")) { if (metadata.ContainsKey("Title")) { title = metadata["Title"] as string; } else if (metadata.ContainsKey("Uri")) { // Use this for audio. Will get the path to the audio file even in the context of a playlist // But with video this will return the wpl file title = metadata["Uri"] as string; } } return string.IsNullOrEmpty(title) ? string.Empty : title; }
private string GetMetaString(MediaMetadata MediaMetadata, string Key) { string retStr = ""; object objStr = ""; MediaMetadata.TryGetValue(Key, out objStr); if (!string.IsNullOrEmpty((string)objStr)) retStr = (string)objStr; return retStr; }
public object this[MediaMetadata mediaMetadata] { get { switch(mediaMetadata) { case MediaMetadata.AlbumArtist: return GetAttributeByName("WM/AlbumArtist"); case MediaMetadata.AlbumSortOrder: return GetAttributeByName("WM/AlbumSortOrder"); case MediaMetadata.AlbumTitle: return GetAttributeByName("WM/AlbumTitle"); case MediaMetadata.AudioFileUrl: return GetAttributeByName("WM/AudioFileURL"); case MediaMetadata.Author: return GetAttributeByName("Author"); case MediaMetadata.BeatsPerMinute: return GetAttributeByName("WM/BeatsPerMinute"); case MediaMetadata.BitRate: return GetAttributeByName("Bitrate"); case MediaMetadata.Composer: return GetAttributeByName("WM/Composer"); case MediaMetadata.Conductor: return GetAttributeByName("WM/Conductor"); case MediaMetadata.ContentDistributor: return GetAttributeByName("WM/ContentDistributor"); case MediaMetadata.Copyright: return GetAttributeByName("Copyright"); case MediaMetadata.CopyrightUrl: return GetAttributeByName("CopyrightURL"); case MediaMetadata.Description: return GetAttributeByName("Description"); case MediaMetadata.Duration: return GetAttributeByName("Duration"); case MediaMetadata.FileSize: return GetAttributeByName("FileSize"); case MediaMetadata.Genre: return GetAttributeByName("WM/Genre"); case MediaMetadata.IsProtected: return GetAttributeByName("Is_Protected"); case MediaMetadata.Lyrics: return GetAttributeByName("WM/Lyrics"); case MediaMetadata.AcoustID: return GetAttributeByName("Acoustid/Id"); case MediaMetadata.MBID: return GetAttributeByName("MusicBrainz/Track Id"); case MediaMetadata.Provider: return GetAttributeByName("WM/Provider"); case MediaMetadata.Publisher: return GetAttributeByName("WM/Publisher"); case MediaMetadata.Text: return GetAttributeByName("WM/Text"); case MediaMetadata.Title: return GetAttributeByName("Title"); case MediaMetadata.TrackNumber: return GetAttributeByName("WM/TrackNumber"); case MediaMetadata.Year: return GetAttributeByName("WM/Year"); default: return null; } } }
public MutableMediaMetadata(string trackId, MediaMetadata metadata) { Metadata = metadata; TrackId = trackId; }