public IMediaFile Open(string file) { int bestHandleLevel = -1; IMediaFile bestMediaFile = null; foreach (IMediaFileFactory factory in mainForm.PackageSystem.MediaFileTypes.Values) { int handleLevel = factory.HandleLevel(file); if (handleLevel < 0) { continue; } try { if (handleLevel > bestHandleLevel) { IMediaFile mFile = factory.Open(file); if (mFile != null) { bestHandleLevel = handleLevel; if (bestMediaFile != null) { bestMediaFile.Dispose(); } bestMediaFile = mFile; } } } catch (Exception ex) { string test = ex.Message; } } return(bestMediaFile); }
/// <summary> /// Deletes the <see cref="IMediaFile"/> in the CMS System. /// </summary> /// <param name="file">The <see cref="IMediaFile"/> to set.</param> public void RemoveMediaFile(IMediaFile file) { if (this.ShouldProcess(file.FileName, "delete")) { this.MediaLibraryService.DeleteMediaFile(file); } }
public static void AttachTo(IMediaFile mediaFile, TimeSpan fadeOnStart, TimeSpan fadeOnEnd, TimeSpan fadeOnPause, TimeSpan fadeOnResume) { Pair <WeakReference, WeakReference> pair; VolumeFader fader; fader = new VolumeFader(mediaFile, fadeOnStart, fadeOnEnd, fadeOnPause, fadeOnResume); pair = new Pair <WeakReference, WeakReference>(new WeakReference(fader), new WeakReference(mediaFile)); for (int i = 0; i < m_VolumeFaders.Count; i++) { Pair <WeakReference, WeakReference> pair2; pair2 = (Pair <WeakReference, WeakReference>)m_VolumeFaders[i]; if (((WeakReference)pair2.Left).Target == null || ((WeakReference)pair2.Right).Target == null) { m_VolumeFaders[i] = pair; return; } } m_VolumeFaders.Add(pair); }
public IData GetParent(IData data) { IData parent = null; if (data is IMediaFile) { IMediaFile file = (IMediaFile)data; parent = (from item in DataFacade.GetData <IMediaFileFolder>() where item.Path == file.FolderPath && item.StoreId == file.StoreId select item).FirstOrDefault(); } else if (data is IMediaFileFolder) { IMediaFileFolder folder = (IMediaFileFolder)data; int lastIndex = folder.Path.LastIndexOf('/'); if (lastIndex == 0) { return(null); } string parentPath = folder.Path.Substring(0, lastIndex); parent = (from item in DataFacade.GetData <IMediaFileFolder>() where item.Path == parentPath && item.StoreId == folder.StoreId select item).FirstOrDefault(); } else { throw new ArgumentException("Must be either of type IMediaFile or IMediaFileFolder", "data"); } return(parent); }
public void UpdateMetadata(IMediaFile currentTrack) { MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder(); if (currentTrack != null) { builder .PutString(MediaMetadata.MetadataKeyAlbum, currentTrack.Metadata.Album) .PutString(MediaMetadata.MetadataKeyArtist, currentTrack.Metadata.Artist) .PutString(MediaMetadata.MetadataKeyTitle, currentTrack.Metadata.Title); } else { builder .PutString(MediaMetadata.MetadataKeyAlbum, Session?.Controller?.Metadata?.GetString(MediaMetadata.MetadataKeyAlbum)) .PutString(MediaMetadata.MetadataKeyArtist, Session?.Controller?.Metadata?.GetString(MediaMetadata.MetadataKeyArtist)) .PutString(MediaMetadata.MetadataKeyTitle, Session?.Controller?.Metadata?.GetString(MediaMetadata.MetadataKeyTitle)); } var resources = _applicationContext.Resources; //TODO add option to use either PVL, Poniverse, Station or Album art to Options (and here) //builder.PutBitmap(MediaMetadata.MetadataKeyAlbumArt, currentTrack?.Metadata.AlbumArt as Bitmap); // Uncomment these lines and replace the "splash" with your own drawable resource to use a lock screen pic //var id = Resource.Drawable.ic_vol_type_tv_dark; //var art = BitmapFactory.DecodeResource(resources, id); //builder.PutBitmap(MediaMetadata.MetadataKeyAlbumArt, art); Session?.SetMetadata(builder.Build()); }
private IWatermarkConfiguration GetWatermarkConfigOrDefault(NameValueCollection queryString) { try { IMediaFile mediaFile = MediaUrlHelper.GetFileFromQueryString(queryString); using (var connection = new DataConnection()) { IQueryable <IWatermarkConfiguration> configs = connection.Get <IWatermarkConfiguration>(); foreach (IWatermarkConfiguration config in configs) { IMediaFileFolder mediaFolder = connection.Get <IMediaFileFolder>().SingleOrDefault(mf => mf.KeyPath == config.TargetMediaFolderPath); if (mediaFolder != null && mediaFile.CompositePath.StartsWith(mediaFolder.CompositePath)) { return(config); } } } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } return(null); }
public async Task Play(IMediaFile mediaFile) { _loadMediaTaskCompletionSource = new TaskCompletionSource <bool>(); try { if (_currentMediaSource != null) { _currentMediaSource.StateChanged -= MediaSourceOnStateChanged; _currentMediaSource.OpenOperationCompleted -= MediaSourceOnOpenOperationCompleted; } // Todo: sync this with the playback queue var mediaPlaybackList = new MediaPlaybackList(); _currentMediaSource = await CreateMediaSource(mediaFile); _currentMediaSource.StateChanged += MediaSourceOnStateChanged; _currentMediaSource.OpenOperationCompleted += MediaSourceOnOpenOperationCompleted; var item = new MediaPlaybackItem(_currentMediaSource); mediaPlaybackList.Items.Add(item); _player.Source = mediaPlaybackList; _player.Play(); } catch (Exception) { Debug.WriteLine("Unable to open url: " + mediaFile.Url); } }
private void ValidateStep1Bindings_Finish(object sender, ConditionalEventArgs e) { ValidateStep1Bindings_Next(sender, e); if (!e.Result) { return; } UploadedFile uploadedFile = this.GetBinding <UploadedFile>("UploadedFile"); string filename = uploadedFile.FileName; bool allowOverwrite = this.GetBinding <bool>("AllowOverwrite"); IMediaFile existingFile = GetExistingFile(this.FolderPath, filename); if (existingFile != null && !allowOverwrite) { this.ShowFieldMessage("UploadedFile", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.FileExists.Message}"); e.Result = false; return; } string compositePath = IMediaFileExtensions.GetCompositePath(this.StoreId, this.FolderPath, filename); if (compositePath.Length > 2048) { this.ShowFieldMessage("UploadedFile", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.TotalFilenameToLong.Message}"); e.Result = false; return; } e.Result = true; }
private void SetMetadata(IMediaFile mediaFile) { _builder.SetContentTitle(mediaFile?.Metadata?.Title ?? string.Empty); _builder.SetContentText(mediaFile?.Metadata?.Artist ?? string.Empty); _builder.SetContentInfo(mediaFile?.Metadata?.Album ?? string.Empty); _builder.SetLargeIcon(mediaFile?.Metadata?.Art as Bitmap); }
public void UpdateNotifications(IMediaFile mediaFile, MediaPlayerStatus status) { try { var isPlaying = status == MediaPlayerStatus.Playing || status == MediaPlayerStatus.Buffering; var nm = NotificationManagerCompat.From(_appliactionContext); if (nm != null && _builder != null) { SetMetadata(mediaFile); AddActionButtons(isPlaying); _builder.SetOngoing(isPlaying); nm.Notify(MediaServiceBase.NotificationId, _builder.Build()); } else { StartNotification(mediaFile, isPlaying, false); } } catch (Exception ex) { Console.WriteLine(ex.Message); StopNotifications(); } }
public void UpdateNotifications(IMediaFile mediaFile, MediaPlayerStatus status) { try { var isPlaying = status == MediaPlayerStatus.Playing || status == MediaPlayerStatus.Buffering; var isPersistent = status == MediaPlayerStatus.Playing || status == MediaPlayerStatus.Buffering || status == MediaPlayerStatus.Paused; var nm = NotificationManagerCompat.From(_applicationContext); if (nm != null && _builder != null) { SetMetadata(mediaFile); AddActionButtons(isPlaying); _builder.SetOngoing(isPersistent); var notification = _builder.Build(); CheckSmallIconInMIUI(notification); nm.Notify(_notificationId, notification); } else { StartNotification(mediaFile, isPlaying, false); } } catch (Exception ex) { Console.WriteLine(ex.Message); StopNotifications(); } }
public override async Task Play(IMediaFile mediaFile = null) { await base.Play(mediaFile); if (mediaFile != null) { try { _mediaPlayer.PrepareAsync(); } catch (Java.Lang.IllegalStateException) { int retryCount = 0; do { await Task.Delay(250); try { _mediaPlayer.Reset(); await SetMediaPlayerDataSource(); _mediaPlayer.PrepareAsync(); } catch (Java.Lang.IllegalStateException) { retryCount++; continue; } return; } while (retryCount < 10); } } }
private Bitmap GetTrackCover(IMediaFile currentTrack) { string albumFolder = GetCurrentSongFolder(currentTrack); if (albumFolder == null) { return(null); } if (!albumFolder.EndsWith("/")) { albumFolder += "/"; } System.Uri baseUri = new System.Uri(albumFolder); var albumArtPath = TryGetAlbumArtPathByFilename(baseUri, "Folder.jpg"); if (albumArtPath == null) { albumArtPath = TryGetAlbumArtPathByFilename(baseUri, "Cover.jpg"); if (albumArtPath == null) { albumArtPath = TryGetAlbumArtPathByFilename(baseUri, "AlbumArtSmall.jpg"); if (albumArtPath == null) { return(null); } } } Bitmap bitmap = BitmapFactory.DecodeFile(albumArtPath); return(bitmap ?? BitmapFactory.DecodeResource(_resources, Resource.Drawable.IcMediaPlay)); }
public void SetTrackAsCurrent(IMediaFile item) { if (_queue.Contains(item)) { Index = _queue.IndexOf(item); } }
static string GetExtension(IMediaFile mediaFile) { string extension; try { var fileName = mediaFile.FileName; foreach (var ch in Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(ch, '_'); } extension = Path.GetExtension(fileName); } catch (ArgumentException) { return(null); } if (string.IsNullOrEmpty(extension)) { extension = MimeTypeInfo.GetExtensionFromMimeType(mediaFile.MimeType); } return(extension); }
/// <summary> /// Checks if player just paused. /// </summary> /// <param name="mediaFile">The media file.</param> private async Task <bool> CheckIfFileAlreadyIsPlaying(IMediaFile mediaFile) { var isNewFile = CurrentFile == null || string.IsNullOrEmpty(mediaFile?.Url) || mediaFile?.Url != CurrentFile?.Url; //New File selected if (isNewFile) { return(await Task.FromResult(false)); } //Same file selected => seek to start if (MediaPlayerState != PlaybackStateCompat.StatePaused && !ManuallyPaused) { await Seek(TimeSpan.Zero); return(await Task.FromResult(true)); } //just paused.. restart playback! if (MediaPlayerState == PlaybackStateCompat.StatePaused && ManuallyPaused) { ManuallyPaused = false; SessionManager.UpdatePlaybackState(PlaybackStateCompat.StatePlaying, Position.Seconds); SessionManager.UpdateMetadata(mediaFile); SessionManager.NotificationManager.StartNotification(mediaFile); CurrentFile = mediaFile; Resume(); return(await Task.FromResult(true)); } return(await Task.FromResult(false)); }
private void RegisterCurrentTriggers() { var updateProperty = new Action(() => { IMediaFile current = null; if (Count - 1 >= Index && Index >= 0) { current = _queue[Index]; } if (_current != current) { _current = current; OnPropertyChanged(nameof(Current)); } }); PropertyChanged += (sender, e) => { if (e.PropertyName == nameof(Index)) { updateProperty(); } }; _queue.CollectionChanged += (sender, e) => { updateProperty(); }; if (Count - 1 >= Index && Index >= 0) { _current = _queue[Index]; } }
public async Task<IMediaFile> ExtractMediaInfo(IMediaFile mediaFile) { if (mediaFile.MetadataExtracted) return mediaFile; MediaMetadataRetriever metaRetriever = await GetMetadataRetriever(mediaFile); SetMetadata(mediaFile, metaRetriever); byte[] imageByteArray = null; try { imageByteArray = metaRetriever.GetEmbeddedPicture(); } catch (Exception ex) { Console.WriteLine(ex.Message); } if (imageByteArray == null) { mediaFile.Metadata.AlbumArt = GetTrackCover(mediaFile); } else { try { mediaFile.Metadata.AlbumArt = await BitmapFactory.DecodeByteArrayAsync(imageByteArray, 0, imageByteArray.Length); } catch (Java.Lang.OutOfMemoryError) { mediaFile.Metadata.AlbumArt = null; throw; } } mediaFile.MetadataExtracted = true; return mediaFile; }
/// <summary> /// Updates the metadata on the lock screen /// </summary> /// <param name="currentTrack"></param> internal void UpdateMetadata(IMediaFile currentTrack) { MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder(); if (currentTrack != null) { builder .PutString(MediaMetadata.MetadataKeyAlbum, currentTrack.Metadata.Artist) .PutString(MediaMetadata.MetadataKeyArtist, currentTrack.Metadata.Artist) .PutString(MediaMetadata.MetadataKeyTitle, currentTrack.Metadata.Title); } else { builder .PutString(MediaMetadata.MetadataKeyAlbum, CurrentSession?.Controller?.Metadata?.GetString(MediaMetadata.MetadataKeyAlbum)) .PutString(MediaMetadata.MetadataKeyArtist, CurrentSession?.Controller?.Metadata?.GetString(MediaMetadata.MetadataKeyArtist)) .PutString(MediaMetadata.MetadataKeyTitle, CurrentSession?.Controller?.Metadata?.GetString(MediaMetadata.MetadataKeyTitle)); } builder.PutBitmap(MediaMetadata.MetadataKeyAlbumArt, currentTrack?.Metadata.AlbumArt as Bitmap); CurrentSession?.SetMetadata(builder.Build()); }
public void PlayMedia() { IMediaFile _mtype = (IMediaFile)Assembly.Load(ConfigurationManager.AppSettings).CreateInstance(mediaName); IPlayer _player = (IPlayer)Assembly.Load(assemName).CreateInstance(playerName); _player.Play(_mtype); }
public async Task <IMediaFile> ExtractMediaInfo(IMediaFile mediaFile) { if (mediaFile.Availability == ResourceAvailability.Local) { var file = await StorageFile.GetFileFromPathAsync(mediaFile.Url); switch (mediaFile.Type) { case MediaFileType.Audio: await SetAudioInfo(file, mediaFile); break; case MediaFileType.Video: await SetVideoInfo(file, mediaFile); break; } await SetAlbumArt(file, mediaFile); } mediaFile.MetadataExtracted = true; return(mediaFile); }
private void ValidateStep2Bindings(object sender, ConditionalEventArgs e) { string filename = this.GetBinding <string>("Filename"); bool allowOverwrite = this.GetBinding <bool>("AllowOverwrite"); IMediaFile existingFile = GetExistingFile(this.FolderPath, filename); if ((existingFile != null) && (allowOverwrite == false)) { this.ShowFieldMessage("Filename", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.FileExists.Message}"); e.Result = false; return; } string compositePath = IMediaFileExtensions.GetCompositePath(this.StoreId, this.FolderPath, filename); if (compositePath.Length > 2048) { this.ShowFieldMessage("Filename", "${Composite.Management, Website.Forms.Administrative.AddNewMediaFile.TotalFilenameToLong.Message}"); e.Result = false; return; } e.Result = true; }
private async void UpdateInfoFromMediaFile(IMediaFile mediaFile) { var updater = _systemMediaTransportControls.DisplayUpdater; switch (mediaFile.Type) { case MediaFileType.AudioUrl: break; case MediaFileType.AudioFile: await updater.CopyFromFileAsync(MediaPlaybackType.Music, await StorageFile.GetFileFromPathAsync(mediaFile.Url)); break; case MediaFileType.VideoUrl: break; case MediaFileType.VideoFile: await updater.CopyFromFileAsync(MediaPlaybackType.Video, await StorageFile.GetFileFromPathAsync(mediaFile.Url)); break; case MediaFileType.Other: break; default: throw new ArgumentOutOfRangeException(); } updater.Update(); }
private void ValidateInputs(object sender, ConditionalEventArgs e) { IMediaFile file = this.GetDataItemFromEntityToken <IMediaFile>(); string filename = this.GetBinding <string>("FileDataFileName"); string compositePath = IMediaFileExtensions.GetCompositePath(file.StoreId, file.FolderPath, filename); if (compositePath.Length > 2048) { this.ShowFieldMessage("FileDataFileName", "${Composite.Management, Website.Forms.Administrative.EditMediaFile.TotalFilenameToLong.Message}"); e.Result = false; return; } Guid mediaFileId = file.Id; if (DataFacade.GetData <IMediaFile>() .Any(mediaFile => string.Compare(mediaFile.CompositePath, compositePath, StringComparison.InvariantCultureIgnoreCase) == 0 && mediaFile.Id != mediaFileId)) { this.ShowFieldMessage("FileDataFileName", "${Composite.Management, Website.Forms.Administrative.EditMediaFile.FileExists.Message}"); e.Result = false; return; } e.Result = true; }
/// <summary> /// When we start on the foreground we will present a notification to the user /// When they press the notification it will take them to the main page so they can control the music /// </summary> public void StartNotification(IMediaFile mediaFile, bool mediaIsPlaying, bool canBeRemoved) { var icon = (_appliactionContext.Resources?.GetIdentifier("xam_mediamanager_notify_ic", "drawable", _appliactionContext?.PackageName)).GetValueOrDefault(0); _notificationStyle.SetMediaSession(_sessionToken); _notificationStyle.SetCancelButtonIntent(_pendingCancelIntent); _builder = new NotificationCompat.Builder(_appliactionContext) { MStyle = _notificationStyle }; _builder.SetSmallIcon(icon != 0 ? icon : _appliactionContext.ApplicationInfo.Icon); _builder.SetContentIntent(_pendingIntent); _builder.SetOngoing(mediaIsPlaying); _builder.SetVisibility(1); SetMetadata(mediaFile); AddActionButtons(mediaIsPlaying); if (_builder.MActions.Count >= 3) { ((NotificationCompat.MediaStyle)(_builder.MStyle)).SetShowActionsInCompactView(0, 1, 2); } NotificationManagerCompat.From(_appliactionContext) .Notify(MediaServiceBase.NotificationId, _builder.Build()); }
public IMediaFile Open(string file) { int bestHandleLevel = -1; IMediaFile bestMediaFile = null; foreach (IMediaFileFactory factory in mainForm.PackageSystem.MediaFileTypes.Values) { int handleLevel = factory.HandleLevel(file); if (handleLevel < 0) { continue; } IMediaFile mFile = factory.Open(file); if (mFile != null && handleLevel > bestHandleLevel) { bestHandleLevel = handleLevel; bestMediaFile = mFile; } else if (mFile != null) { mFile.Dispose(); } } return(bestMediaFile); }
private static MediaUrlData ParseRenderUrl(string relativeUrl, out UrlKind urlKind) { try { var queryParameters = new UrlBuilder(relativeUrl).GetQueryParameters(); IMediaFile mediaFile = MediaUrlHelper.GetFileFromQueryString(queryParameters); Verify.IsNotNull(mediaFile, "failed to get file from a query string"); urlKind = UrlKind.Renderer; queryParameters.Remove("id"); queryParameters.Remove("i"); queryParameters.Remove("src"); queryParameters.Remove("store"); return(new MediaUrlData { MediaId = mediaFile.Id, MediaStore = mediaFile.StoreId, QueryParameters = queryParameters }); } catch (Exception) { urlKind = UrlKind.Undefined; return(null); } }
public override async Task Play(IMediaFile mediaFile = null) { await base.Play(mediaFile); _mediaPlayer.PlayWhenReady = true; ManuallyPaused = false; }
public void PlayMedia() { IMediaFile _mtype = Assembly.Load(ConfigurationManager.AppSettings["AssemName"]).CreateInstance(ConfigurationManager.AppSettings["MediaName"]); IPlayer _player = Assembly.Load(ConfigurationManager.AppSettings["AssemName"]).CreateInstance(ConfigurationManager.AppSettings["PlayerName"]); _player.Play(_mtype); }
private async Task<MediaMetadataRetriever> GetMetadataRetriever(IMediaFile currentFile) { MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); switch (currentFile.Type) { case MediaFileType.AudioUrl: await metaRetriever.SetDataSourceAsync(currentFile.Url, _requestHeaders); break; case MediaFileType.VideoUrl: break; case MediaFileType.AudioFile: Java.IO.File file = new Java.IO.File(currentFile.Url); Java.IO.FileInputStream inputStream = new Java.IO.FileInputStream(file); await metaRetriever.SetDataSourceAsync(inputStream.FD); break; case MediaFileType.VideoFile: break; case MediaFileType.Other: break; default: throw new ArgumentOutOfRangeException(); } return metaRetriever; }
private async Task <MediaMetadataRetriever> GetMetadataRetriever(IMediaFile currentFile) { MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); switch (currentFile.Type) { case MediaFileType.AudioUrl: await metaRetriever.SetDataSourceAsync(currentFile.Url, _requestHeaders); break; case MediaFileType.VideoUrl: break; case MediaFileType.AudioFile: Java.IO.File file = new Java.IO.File(currentFile.Url); Java.IO.FileInputStream inputStream = new Java.IO.FileInputStream(file); await metaRetriever.SetDataSourceAsync(inputStream.FD); break; case MediaFileType.VideoFile: break; case MediaFileType.Other: break; default: throw new ArgumentOutOfRangeException(); } return(metaRetriever); }
public void Insert(int index, IMediaFile item) { if (IsShuffled) { _unshuffledQueue.Add(item); } var changedIndexInternally = false; if (index <= Index || Index == -1) { _index++; changedIndexInternally = true; } try { _queue.Insert(index, item); } catch (Exception) { if (changedIndexInternally) { _index--; } throw; } // Only to fire off the index when also the property Current is updated (by triggering RemoveAt()) if (changedIndexInternally) { OnPropertyChanged(nameof(Index)); } }
private void SetTranscodeParameters() { IVideoFormat videoFormat = Preview.VideoFormat; IAudioFormat audioFormat = Preview.AudioFormat; mediaComposer.addSourceFile(new File(Preview.File)); IMediaFile mediaFile = mediaComposer.getSourceFiles()[0]; var sourceFiles = mediaComposer.getSourceFiles(); if (sourceFiles.Count != 0) { double mul = Preview.Duration / 100; long trimStartTime = (long)(Preview.SegmentStart * mul); long trimStopTime = (long)(Preview.SegmentEnd * mul); var sourceFile = sourceFiles[0]; sourceFile.addSegment(Segment.fromMicroSeconds(trimStartTime, trimStopTime)); } ComboBoxItem framerateItem = (ComboBoxItem)FramerateSelect.SelectedItem; String videoProfile = ((ComboBoxItem)ProfileSelect.SelectedItem).Content.ToString(); var match = Regex.Match(videoProfile, @"\(([0-9]+)x([0-9]+)\)"); uint width = uint.Parse(match.Groups[1].Value); uint height = uint.Parse(match.Groups[2].Value); uint framerate = uint.Parse(framerateItem.Content.ToString()); uint bitrate = (uint)(BitrateSelect.Value * 1000); if (videoFormat != null) { var vFormat = new WinRtVideoFormat(videoMimeType, width, height) { bitrate = bitrate }; vFormat.frameRate.Numerator = framerate; vFormat.frameRate.Denominator = 1; mediaComposer.setTargetVideoFormat(vFormat); } if (audioFormat != null) { var aFormat = new WinRtAudioFormat(audioMimeType) { bitrate = audioFormat.bitrate, bitsPerSample = audioFormat.bitsPerSample, channelCount = audioFormat.channelCount, sampleRate = audioFormat.sampleRate }; mediaComposer.setTargetAudioFormat(aFormat); } }
static bool ExtractText(string sourceFile, string targetFile, IMediaFile mediaFile) { var exePath = PathUtil.Resolve(IFilterExecutableRelativePath); var workingDirectory = Path.GetDirectoryName(exePath); string stdout, stderr; int exitCode; using (var process = new Process { StartInfo = { WorkingDirectory = workingDirectory, FileName = "\"" + exePath + "\"", Arguments = $"\"{sourceFile}\" \"{targetFile}\"", RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true, StandardOutputEncoding = Encoding.UTF8, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden } }) { process.Start(); stdout = process.StandardOutput.ReadToEnd(); stderr = process.StandardError.ReadToEnd(); process.WaitForExit(); exitCode = process.ExitCode; } if (exitCode != 0) { var msg = $"Failed to parse the content of the media file '{Path.GetFileName(mediaFile.FileName)}'."; if ((uint)exitCode == 0x80004005 /*E_FAIL*/) { msg += " Unspecified error."; } else if ((uint)exitCode == 0x80004002 /*E_NOINTERFACE*/) { msg += " IFilter not found for the given file extension."; } else { msg += $"\r\nExit Code: {exitCode}\r\nOutput: {stdout}" + (!string.IsNullOrEmpty(stderr) ? $"\r\nError: {stderr}" : ""); } Log.LogWarning(LogTitle, msg); return(false); } return(File.Exists(targetFile)); }
public ChannelInfo(Channel channel, IMediaFile file, Action playNextFileAction) { this.Channel = channel; this.Channel.getSystemObject(out system).ERRCHECK(); this.File = file; this.playNextFileAction = playNextFileAction; this.channelEndCallback = new FMOD.CHANNEL_CALLBACK(ChannelEndCallback); this.Channel.setCallback(this.channelEndCallback).ERRCHECK(); this.Volume = 0f; }
/// <exclude /> public static string GetUrl(IMediaFile file, bool isInternal, bool downloadableMedia) { string url = MediaUrls.BuildUrl(file, isInternal ? UrlKind.Internal : UrlKind.Public); if (!downloadableMedia) return url; var urlBuilder = new UrlBuilder(url); urlBuilder["download"] = "true"; return urlBuilder.ToString(); }
public static XElement UploadDocument(IMediaFile media) { var data = IssuuApi.NewQuery("issuu.document.upload"); data.Add("name", media.GetName()); data.Add("title", media.Title); IssuuApi.Sign(data); var document = GetDocument(WebRequestFacade.UploadFileEx("http://upload.issuu.com/1_0", media.GetReadStream(), media.GetOrgName(), "file", data)); document.SetAttributeValue("publishing", "true"); return document; }
public static QuestionFile CreateQuestionFile(IMediaFile mediaFile) { if (mediaFile == null) { throw new ArgumentNullException("mediaFile","параметр равен null"); } if (mediaFile.ID == null) { throw new ArgumentOutOfRangeException("mediaFile.ID","ID IMediaFile = null"); } return new QuestionFile() {FileID = mediaFile.ID}; }
public static XElement GetDocument(IMediaFile media) { ServicePoint servicePoint = ServicePointManager.FindServicePoint(new Uri("http://api.issuu.com/1_0")); servicePoint.Expect100Continue = false; System.Net.ServicePointManager.Expect100Continue = false; var data = IssuuApi.NewQuery("issuu.documents.list"); data.Add("orgDocName", media.GetOrgName()); IssuuApi.Sign(data); var client = new System.Net.WebClient(); byte[] responseArray = client.UploadValues("http://api.issuu.com/1_0", data); return GetDocument(Encoding.ASCII.GetString(responseArray)); }
/// <exclude /> public WorkflowMediaFile(IMediaFile file) { Id = file.Id; StoreId = file.StoreId; Title = file.Title; Culture = file.Culture; CreationTime = file.CreationTime; DataSourceId = file.DataSourceId; Description = file.Description; FileName = file.FileName; FolderPath = file.FolderPath; IsReadOnly = file.IsReadOnly; LastWriteTime = file.LastWriteTime; Length = file.Length; MimeType = file.MimeType; }
public async Task<IMediaFile> ExtractMediaInfo(IMediaFile mediaFile) { switch (mediaFile.Type) { case MediaFileType.AudioUrl: case MediaFileType.AudioFile: await GetAudioInfo(mediaFile); return mediaFile; case MediaFileType.VideoUrl: case MediaFileType.VideoFile: return await GetVideoInfo(mediaFile); case MediaFileType.Other: break; default: throw new ArgumentOutOfRangeException(); } return await Task.FromResult(mediaFile); }
public async Task<IMediaFile> ExtractMediaInfo(IMediaFile mediaFile) { try { var assetsToLoad = new List<string> { AVMetadata.CommonKeyArtist, AVMetadata.CommonKeyTitle, AVMetadata.CommonKeyArtwork }; var nsUrl = new NSUrl(mediaFile.Url); // Default title to filename mediaFile.Metadata.Title = nsUrl.LastPathComponent; var asset = AVAsset.FromUrl(nsUrl); await asset.LoadValuesTaskAsync(assetsToLoad.ToArray()); foreach (var avMetadataItem in asset.CommonMetadata) { if (avMetadataItem.CommonKey == AVMetadata.CommonKeyArtist) { mediaFile.Metadata.Artist = ((NSString) avMetadataItem.Value).ToString(); } else if (avMetadataItem.CommonKey == AVMetadata.CommonKeyTitle) { mediaFile.Metadata.Title = ((NSString) avMetadataItem.Value).ToString(); } else if (avMetadataItem.CommonKey == AVMetadata.CommonKeyArtwork) { #if __IOS__ || __TVOS__ var image = UIImage.LoadFromData(avMetadataItem.DataValue); mediaFile.Metadata.AlbumArt = image; #endif } } mediaFile.MetadataExtracted = true; return mediaFile; } catch (Exception) { return mediaFile; } }
private async Task<IMediaFile> GetVideoInfo(IMediaFile mediaFile) { if (mediaFile.Type == MediaFileType.VideoFile) { var file = await StorageFile.GetFileFromPathAsync(mediaFile.Url); var musicProperties = await file.Properties.GetVideoPropertiesAsync(); mediaFile.Metadata.Title = musicProperties.Title; mediaFile.Metadata.Album = string.Empty; mediaFile.Metadata.Artist = string.Empty; var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView); if (thumbnail != null && thumbnail.Type == ThumbnailType.Image) { BitmapSource bitmap = new BitmapImage(); await bitmap.SetSourceAsync(thumbnail); mediaFile.Metadata.AlbumArt = bitmap; } } mediaFile.MetadataExtracted = true; return mediaFile; }
/// <summary> /// When we start on the foreground we will present a notification to the user /// When they press the notification it will take them to the main page so they can control the music /// </summary> public void StartNotification(IMediaFile mediaFile, bool mediaIsPlaying, bool canBeRemoved) { _notificationStyle.SetMediaSession(_sessionToken); _notificationStyle.SetCancelButtonIntent(_pendingCancelIntent); _notificationStyle.SetShowActionsInCompactView(0, 1, 2); _builder = new NotificationCompat.Builder(_appliactionContext) { MStyle = _notificationStyle }; _builder.SetSmallIcon(_appliactionContext.ApplicationInfo.Icon); _builder.SetContentIntent(_pendingIntent); _builder.SetOngoing(true); _builder.SetVisibility(1); SetMetadata(mediaFile); AddActionButtons(mediaIsPlaying); NotificationManagerCompat.From(_appliactionContext) .Notify(MediaServiceBase.NotificationId, _builder.Build()); }
/// <summary> /// When we start on the foreground we will present a notification to the user /// When they press the notification it will take them to the main page so they can control the music /// </summary> public void StartNotification(IMediaFile mediaFile, bool mediaIsPlaying, bool canBeRemoved) { var icon = (_appliactionContext.Resources?.GetIdentifier("xam_mediamanager_notify_ic", "drawable", _appliactionContext?.PackageName)).GetValueOrDefault(0); _notificationStyle.SetMediaSession(_sessionToken); _notificationStyle.SetCancelButtonIntent(_pendingCancelIntent); _notificationStyle.SetShowActionsInCompactView(0, 1, 2); _builder = new NotificationCompat.Builder(_appliactionContext) { MStyle = _notificationStyle }; _builder.SetSmallIcon(icon != 0 ? icon : _appliactionContext.ApplicationInfo.Icon); _builder.SetContentIntent(_pendingIntent); _builder.SetOngoing(mediaIsPlaying); _builder.SetVisibility(1); SetMetadata(mediaFile); AddActionButtons(mediaIsPlaying); NotificationManagerCompat.From(_appliactionContext) .Notify(MediaServiceBase.NotificationId, _builder.Build()); }
public void StartNotification(IMediaFile mediaFile) { /*if (mediaSessionCompat == null) return; var pendingIntent = PendingIntent.GetActivity(Application.Context, 0, new Intent(Application.Context, typeof(MediaPlayer)), PendingIntentFlags.UpdateCurrent); MediaMetadataCompat currentTrack = mediaControllerCompat.Metadata; Android.Support.V7.App.NotificationCompat.MediaStyle style = new Android.Support.V7.App.NotificationCompat.MediaStyle(); style.SetMediaSession(mediaSessionCompat.SessionToken); Intent intent = new Intent(Application.Context, typeof(MediaPlayerService)); intent.SetAction(ActionStop); PendingIntent pendingCancelIntent = PendingIntent.GetService(Application.Context, 1, intent, PendingIntentFlags.CancelCurrent); style.SetShowCancelButton(true); style.SetCancelButtonIntent(pendingCancelIntent); NotificationCompat.Builder builder = new NotificationCompat.Builder(Application.Context) .SetStyle(style) .SetContentTitle(currentTrack.GetString(MediaMetadata.MetadataKeyTitle)) .SetContentText(currentTrack.GetString(MediaMetadata.MetadataKeyArtist)) .SetContentInfo(currentTrack.GetString(MediaMetadata.MetadataKeyAlbum)) .SetSmallIcon(Resource.Drawable.ButtonStar) .SetLargeIcon(Cover as Bitmap) .SetContentIntent(pendingIntent) .SetShowWhen(false) .SetOngoing(MediaPlayerState == PlaybackStateCompat.StatePlaying) .SetVisibility(NotificationCompat.VisibilityPublic); builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaPrevious, "Previous", ActionPrevious)); AddPlayPauseActionCompat(builder); builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaNext, "Next", ActionNext)); style.SetShowActionsInCompactView(0, 1, 2); NotificationManagerCompat.From(Application.Context).Notify(NotificationId, builder.Build());*/ }
public async Task Play(IMediaFile mediaFile) { _currentMediaFile = mediaFile; await Play(mediaFile.Url, mediaFile.Type); }
/// <summary> /// Initializes a new instance of the <see cref="MediaUrlData"/> class. /// </summary> /// <param name="mediaFile">The media file.</param> public MediaUrlData(IMediaFile mediaFile) { MediaStore = mediaFile.StoreId; MediaId = mediaFile.Id; QueryParameters = new NameValueCollection(); }
/// <summary> /// Returns a media url. /// </summary> /// <param name="mediaFile">The media file.</param> /// <param name="querystring">The querystring.</param> /// <returns></returns> public IHtmlString MediaUrl(IMediaFile mediaFile, IDictionary<string, string> querystring) { return MediaUrl(mediaFile.KeyPath, querystring); }
/// <summary> /// opens a given DGIndex script /// </summary> /// <param name="videoInput">the DGIndex script to be opened</param> private void openVideo(string videoInput, string textBoxName, bool inlineAvs) { this.crop.Checked = false; this.input.Filename = ""; this.originalScript = videoInput; this.originalInlineAvs = inlineAvs; if (player != null) player.Dispose(); bool videoLoaded = showOriginal(); enableControls(videoLoaded); if (videoLoaded) { this.input.Filename = textBoxName; file = player.File; reader = player.Reader; this.fpsBox.Value = (decimal)file.Info.FPS; if (file.Info.FPS.Equals(25.0)) // disable ivtc for pal sources this.tvTypeLabel.Text = "PAL"; else this.tvTypeLabel.Text = "NTSC"; horizontalResolution.Maximum = file.Info.Width; verticalResolution.Maximum = file.Info.Height; horizontalResolution.Value = file.Info.Width; verticalResolution.Value = file.Info.Height; arChooser.Value = file.Info.DAR; cropLeft.Maximum = cropRight.Maximum = file.Info.Width / 2; cropTop.Maximum = cropBottom.Maximum = file.Info.Height / 2; /// Commented out to ensure to keep the source file resolution when opening it /// if (resize.Enabled && resize.Checked) /// suggestResolution.Checked = true; /// -------------------------------------------------------------------------- this.showScript(); } }
/// <summary> /// Returns a media url. /// </summary> /// <param name="mediaFile">The media file.</param> /// <returns></returns> public IHtmlString MediaUrl(IMediaFile mediaFile) { return MediaUrl(mediaFile.KeyPath); }
/// <summary> /// Returns a media url. /// </summary> /// <param name="mediaFile">The media file.</param> /// <param name="querystring">The querystring.</param> /// <returns></returns> public IHtmlString MediaUrl(IMediaFile mediaFile, object querystring) { return MediaUrl(mediaFile.KeyPath, querystring); }
private bool ValidateMediaFile(IMediaFile mediaFile) { if (CurrentFile != null || mediaFile != null) return true; OnMediaFileFailed(new MediaFileFailedEventArgs(new Exception("No mediafile set"), null)); return false; }
private bool SetCurrentPlayListFile(IMediaFile file) { if (file != null) { var fileCollView = this.FirstSimplePlaylistFiles as ICollectionView; if (fileCollView != null) { return fileCollView.MoveCurrentTo(file); } } return false; }
public virtual async Task Play(IMediaFile mediaFile = null) { if(!ValidateMediaFile(mediaFile)) return; bool alreadyPlaying = await CheckIfFileAlreadyIsPlaying(mediaFile); if (alreadyPlaying) return; CurrentFile = mediaFile; bool dataSourceSet; try { InitializePlayer(); SessionManager.InitMediaSession(PackageName, Binder as MediaServiceBinder); dataSourceSet = await SetMediaPlayerDataSource(); } catch (Exception ex) { dataSourceSet = false; OnMediaFileFailed(new MediaFileFailedEventArgs(ex, mediaFile)); } if (dataSourceSet) { try { var focusResult = AudioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain); if (focusResult != AudioFocusRequest.Granted) Console.WriteLine("Could not get audio focus"); AquireWifiLock(); } catch (Exception ex) { OnMediaFileFailed(new MediaFileFailedEventArgs(ex, CurrentFile)); } } }
/// <summary> /// Starts the notification. /// </summary> /// <param name="mediaFile">The media file.</param> public void StartNotification(IMediaFile mediaFile) { StartNotification(mediaFile, true, false); }
private void SetMetadata(IMediaFile mediaFile) { _builder.SetContentTitle(mediaFile?.Metadata?.Title ?? string.Empty); _builder.SetContentText(mediaFile?.Metadata?.Artist ?? string.Empty); _builder.SetContentInfo(mediaFile?.Metadata?.Album ?? string.Empty); _builder.SetLargeIcon(mediaFile?.Metadata?.AlbumArt as Bitmap); }
public async Task Play(IMediaFile mediaFile = null) { if (mediaFile != null) nsUrl = new NSUrl(mediaFile.Url); if (Status == MediaPlayerStatus.Paused) { Status = MediaPlayerStatus.Playing; //We are simply paused so just start again Player.Play(); return; } try { // Start off with the status LOADING. Status = MediaPlayerStatus.Buffering; var nsAsset = AVAsset.FromUrl(nsUrl); var streamingItem = AVPlayerItem.FromAsset(nsAsset); Player.CurrentItem?.RemoveObserver(this, new NSString("status")); Player.ReplaceCurrentItemWithPlayerItem(streamingItem); streamingItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.New, Player.Handle); streamingItem.AddObserver(this, new NSString("loadedTimeRanges"), NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, Player.Handle); Player.CurrentItem.SeekingWaitsForVideoCompositionRendering = true; Player.CurrentItem.AddObserver(this, (NSString)"status", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, notification => MediaFinished?.Invoke(this, new MediaFinishedEventArgs(mediaFile)), Player.CurrentItem); Player.Play(); } catch (Exception ex) { OnMediaFailed(); Status = MediaPlayerStatus.Stopped; //unable to start playback log error Console.WriteLine("Unable to start playback: " + ex); } }