private void UpdateMediaMetadataCompat(MediaMetadataRetriever metaRetriever = null) { if (_mediaSessionCompat != null) { MainActivity.Instance.RunOnUiThread(() => { MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder(); var item = _mediaSessionCompat.SessionToken; if (metaRetriever != null) { builder .PutString(MediaMetadata.MetadataKeyAlbum, metaRetriever.ExtractMetadata(MetadataKey.Album)) .PutString(MediaMetadata.MetadataKeyArtist, metaRetriever.ExtractMetadata(MetadataKey.Artist)) .PutString(MediaMetadata.MetadataKeyDisplayTitle, metaRetriever.ExtractMetadata(MetadataKey.Title)); } else { builder .PutString(MediaMetadata.MetadataKeyAlbum, _queue[_pos].Album) .PutString(MediaMetadata.MetadataKeyArtist, _queue[_pos].Artist) .PutString(MediaMetadata.MetadataKeyDisplayTitle, _queue[_pos].Title); } if (!String.IsNullOrEmpty(_queue[_pos].Image.ToString())) { Bitmap artwork = BitmapFactory.DecodeFile(_queue[_pos].Image.ToString()); builder.PutBitmap(MediaMetadataCompat.MetadataKeyAlbumArt, artwork); builder.PutBitmap(MediaMetadataCompat.MetadataKeyArt, artwork); } _mediaSessionCompat.SetMetadata(builder.Build()); }); } }
public void Start(int pos) { // System.Diagnostics.Debug.WriteLine("Start()"); if (pos >= 0 && pos < _queue.Count && !_isPreparing) { _isPreparing = true; _pos = pos; _getQueuePos(_pos); _player?.Reset(); try { var url = _queue[_pos].Uri; File tempMp3 = File.CreateTempFile(_queue[pos].Artist, ".mp3", CacheDir); tempMp3.DeleteOnExit(); var tt = tempMp3.Length(); FileOutputStream fos = new FileOutputStream(tempMp3); fos.Write(url); fos.Close(); FileInputStream fis = new FileInputStream(tempMp3); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(tempMp3.Path); long duration = Java.Lang.Long.ParseLong(retriever.ExtractMetadata(MetadataKey.Duration)); _queue[_pos].Duration = duration / 1000; retriever.Release(); _player?.SetDataSource(fis.FD); _player?.PrepareAsync(); } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine(e); } } }
void GetMetaData(global::Android.Net.Uri uri, IDictionary <string, string> headers) { Task.Run(() => { var retriever = new MediaMetadataRetriever(); if (uri.Scheme != null && uri.Scheme.StartsWith("http") && headers != null) { try { retriever.SetDataSource(uri.ToString(), headers); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } } else { retriever.SetDataSource(Context, uri); } ExtractMetadata(retriever); MetadataRetrieved?.Invoke(this, EventArgs.Empty); }); }
public static byte[] GetSelectedMediaData(Activity activity, Android.Net.Uri uri) { try { string path = string.Empty; ContentResolver cr = activity.ContentResolver; string type = cr.GetType(uri); if (type.Contains("video")) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(activity, uri); string duration = retriever.ExtractMetadata(MetadataKey.Duration); retriever.Release(); if (!string.IsNullOrEmpty(duration)) { if (Convert.ToInt32(duration) > 30000) { path = VideoHelper.Trim(1, 30000, VideoHelper.GetMediaRealPath(activity, uri)); return(System.IO.File.ReadAllBytes(path)); } } } var stream = activity.ContentResolver.OpenInputStream(uri); return(stream.ReadAsBytes()); } catch (System.Exception ex) { return(null); } }
public async Task <IMediaModel> GenerateThumbImageFromVideo(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel) { IMediaModel returnValue = new MediaModel(); await Task.Run(() => { string outFilePath = System.IO.Path.Combine(argCurrentDataFolder.FullName, argNewMediaModel.OriginalFilePath); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(argExistingMediaModel.MediaStorageFilePath); Bitmap bitmap = retriever.GetFrameAtTime(1000); // try at 1 second as this is often a more flattering image if (bitmap != null) { //Save the bitmap var outStream = new FileStream(outFilePath, FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outStream); outStream.Close(); returnValue = argNewMediaModel; } }); return(returnValue); }
void UpdatePage(string songId) { MediaMetadataRetriever mmr = SongMetadata.GetMetadata(songId); string title = mmr.ExtractMetadata(MetadataKey.Title); string artist = mmr.ExtractMetadata(MetadataKey.Artist); if (title == null || artist == null) { songTitle.Text = AndroidSongsManager.Instance.GetSong(songId).Name.Replace(".mp3", string.Empty); } else { songTitle.Text = title + " - " + artist; } seekbar.CreateSeekBar(); Drawable picture = SongMetadata.GetSongPicture(songId); if (picture != null) { songImg.SetImageDrawable(picture); } else { songImg.SetImageResource(Resource.Drawable.default_song_image); } }
private long getMediaDuration(Uri uri) { var mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.SetDataSource(this, uri); var durationStr = mediaMetadataRetriever.ExtractMetadata(MetadataKey.Duration); return long.Parse(durationStr); }
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 void GetVideoFrames(int viewWidth) { MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); try { mediaMetadataRetriever.SetDataSource(mVideoUri.ToString(), new Dictionary <string, string>()); // Retrieve media data long videoLengthInMs = Convert.ToInt64(mediaMetadataRetriever.ExtractMetadata(MetadataKey.Duration)) * 1000; // Set thumbnail properties (Thumbs are squares) int thumbWidth = mHeightView; int thumbHeight = mHeightView; int numThumbs = (int)Math.Ceiling(((float)viewWidth) / thumbWidth); long interval = videoLengthInMs / numThumbs; for (int i = 0; i < numThumbs; ++i) { Bitmap bitmap = mediaMetadataRetriever.GetFrameAtTime(i * interval, Android.Media.Option.ClosestSync); bitmap = Bitmap.CreateScaledBitmap(bitmap, thumbWidth, thumbHeight, false); mBitmapList.Add(bitmap); } } catch (Exception ex) { Log.Error("Error", ex.ToString()); } finally { mediaMetadataRetriever.Release(); } }
/// <summary> /// /// </summary> /// <param name="dirPath"></param> /// <param name="fileName"></param> /// <param name="url">视频相对路径</param> /// <param name="usecond"></param> public void SaveThumbImage(string dirPath, string fileName, string url, long usecond) { if (string.IsNullOrWhiteSpace(dirPath) || string.IsNullOrWhiteSpace(url)) { return; } try { Java.IO.FileInputStream input = new FileInputStream(dirPath + url); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); //retriever.SetDataSource(url, new Dictionary<string, string>()); retriever.SetDataSource(input.FD); Bitmap bitmap = retriever.GetFrameAtTime(usecond <= 0 ? 2 * 1000 * 1000 : usecond, Option.ClosestSync); if (bitmap != null) { MemoryStream stream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); byte[] bitmapData = stream.ToArray(); System.IO.File.WriteAllBytes(dirPath + fileName, bitmapData); } retriever.Release(); bitmap.Recycle(); } catch (Exception e) { System.Console.WriteLine("===error:" + e); } }
/// <summary> /// Updates the metadata on the lock screen /// </summary> private void UpdateMediaMetadataCompat(MediaMetadataRetriever metaRetriever = null) { if (mediaSessionCompat == null) { return; } MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder(); if (metaRetriever != null) { builder .PutString(MediaMetadata.MetadataKeyAlbum, metaRetriever.ExtractMetadata(MetadataKey.Album)) .PutString(MediaMetadata.MetadataKeyArtist, metaRetriever.ExtractMetadata(MetadataKey.Artist)) .PutString(MediaMetadata.MetadataKeyTitle, metaRetriever.ExtractMetadata(MetadataKey.Title)); } else { builder .PutString(MediaMetadata.MetadataKeyAlbum, mediaSessionCompat.Controller.Metadata.GetString(MediaMetadata.MetadataKeyAlbum)) .PutString(MediaMetadata.MetadataKeyArtist, mediaSessionCompat.Controller.Metadata.GetString(MediaMetadata.MetadataKeyArtist)) .PutString(MediaMetadata.MetadataKeyTitle, mediaSessionCompat.Controller.Metadata.GetString(MediaMetadata.MetadataKeyTitle)); } builder.PutBitmap(MediaMetadata.MetadataKeyAlbumArt, Cover as Bitmap); mediaSessionCompat.SetMetadata(builder.Build()); }
void ExtractMetadata(MediaMetadataRetriever retriever) { int videoWidth = 0; if (int.TryParse(retriever.ExtractMetadata(MetadataKey.VideoWidth), out videoWidth)) { VideoWidth = videoWidth; } int videoHeight = 0; if (int.TryParse(retriever.ExtractMetadata(MetadataKey.VideoHeight), out videoHeight)) { VideoHeight = videoHeight; } long durationMS; string durationString = retriever.ExtractMetadata(MetadataKey.Duration); if (!string.IsNullOrEmpty(durationString) && long.TryParse(durationString, out durationMS)) { DurationTimeSpan = TimeSpan.FromMilliseconds(durationMS); } else { DurationTimeSpan = null; } }
public bool NeedCompress(string srcPath, int bitrateMode = 10) { try { //Get video metada var mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.SetDataSource(srcPath); string bitrateData = mediaMetadataRetriever.ExtractMetadata(Android.Media.MetadataKey.Bitrate); string videoHeight = mediaMetadataRetriever.ExtractMetadata(Android.Media.MetadataKey.VideoHeight); string videoWidth = mediaMetadataRetriever.ExtractMetadata(Android.Media.MetadataKey.VideoWidth); bitrateMode = bitrateMode == 10 ? bitrateMode10 : bitrateMode2; if (!string.IsNullOrEmpty(bitrateData)) { int bitrate = 0; int.TryParse(bitrateData, out bitrate); bitrate /= 1024; return(bitrate > bitrateMode); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return(false); }
public static Bitmap GetThumbnailFromVideo(Uri uri, long timeMs) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(uri.ToString()); return(retriever.GetFrameAtTime(timeMs * 1000)); }
public byte[] GetVideoThumbnailFromFile(string path) { var retriever = new MediaMetadataRetriever(); retriever.SetDataSource(path); return(GetImageSource(retriever)); }
public override void SetVideoPath(string path) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(path); ExtractMetadata(retriever); base.SetVideoPath(path); }
public byte[] GetVideoThumbnailFromWebUri(string url) { var retriever = new MediaMetadataRetriever(); retriever.SetDataSource(url, new Dictionary <string, string>()); return(GetImageSource(retriever)); }
public static MediaMetadataRetriever GetMetadata(string id) { MediaMetadataRetriever metadata = new MediaMetadataRetriever(); string fileName = FileManager.PATH + AndroidSongsManager.Instance.GetSong(id).Name; metadata.SetDataSource(fileName); return(metadata); }
public TimeSpan GetVideoDuration(string path) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(path); var duration = retriever.ExtractMetadata(MetadataKey.Duration); double durationMillisec = Convert.ToDouble(duration); retriever.Dispose(); return(TimeSpan.FromMilliseconds(durationMillisec)); }
public override void SetVideoPath(string path) { if (System.IO.File.Exists(path)) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(path); ExtractMetadata(retriever); } base.SetVideoPath(path); }
private async Task PrepareAndPlayMediaPlayerAsync() { try { if (NativeVersion.IsAtLeast(21)) { MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); await mediaPlayer.SetDataSourceAsync(ApplicationContext, AndroidNet.Uri.Parse(AudioUrl)); await metaRetriever.SetDataSourceAsync(AudioUrl, new Dictionary <string, string>()); var focusResult = audioManager.RequestAudioFocus(new AudioFocusRequestClass .Builder(AudioFocus.Gain) .SetOnAudioFocusChangeListener(this) .Build()); if (focusResult != AudioFocusRequest.Granted) { // Could not get audio focus Console.WriteLine("Could not get audio focus"); } UpdatePlaybackState(PlaybackStateCode.Buffering); mediaPlayer.PrepareAsync(); AquireWifiLock(); UpdateMediaMetadataCompat(metaRetriever); StartNotification(); byte[] imageByteArray = metaRetriever.GetEmbeddedPicture(); if (imageByteArray == null) { Cover = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.player_play); } else { Cover = await BitmapFactory.DecodeByteArrayAsync(imageByteArray, 0, imageByteArray.Length); } } } catch (Exception ex) { UpdatePlaybackState(PlaybackStateCode.Stopped); mediaPlayer.Reset(); mediaPlayer.Release(); mediaPlayer = null; // Unable to start playback log error Console.WriteLine(ex); } }
public int GetVideoLength(MediaFile media) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(media.Path); var length = retriever.ExtractMetadata(MetadataKey.Duration); var lengthseconds = Convert.ToInt32(length) / 1000; TimeSpan t = TimeSpan.FromSeconds(lengthseconds); // var timeformat = t.Seconds; return(t.Seconds); }
string GetSelectedSongTitle() { MediaMetadataRetriever metadata = SongMetadata.GetMetadata(selectedSong.Id); string title = metadata.ExtractMetadata(MetadataKey.Title); if (title == null) { title = selectedSong.Name.Replace(".mp3", string.Empty); } return(title); }
public async Task CompressVideo(string srcPath, string destPath, int bitrateMode = 10) { await Task.Delay(10); try { //Get the video metadata var mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.SetDataSource(srcPath); string bitrateData = mediaMetadataRetriever.ExtractMetadata(Android.Media.MetadataKey.Bitrate); string videoHeight = mediaMetadataRetriever.ExtractMetadata(Android.Media.MetadataKey.VideoHeight); string videoWidth = mediaMetadataRetriever.ExtractMetadata(Android.Media.MetadataKey.VideoWidth); //Define default quality compress var videoQuality = VideoQuality.High; bitrateMode = bitrateMode == 10 ? bitrateMode10 : bitrateMode2; if (!string.IsNullOrEmpty(bitrateData)) { int bitrate = 0; int.TryParse(bitrateData, out bitrate); bitrate /= 1024; if (bitrate > bitrateMode2) { float reduce = (float)bitrate / (float)bitrateMode2; if (reduce > 6) { videoQuality = VideoQuality.Low; } else if (reduce > 3) { videoQuality = VideoQuality.Medium; } } } var listener = new CompressionListener(); listener.ProgressPercent += Percent; listener.Fail += Fail; listener.Success += (sender, e) => { Success(this, true); }; VideoCompressor.Start(srcPath, destPath, listener, videoQuality, false, false); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public async Task <Song> ParseAsync(File path) { var retriever = new MediaMetadataRetriever(); await retriever.SetDataSourceAsync(path.Path); var title = retriever.ExtractMetadata(MetadataKey.Title); var album = retriever.ExtractMetadata(MetadataKey.Album); var artist = retriever.ExtractMetadata(MetadataKey.Artist); var albumArtist = retriever.ExtractMetadata(MetadataKey.Albumartist); var coverBitmap = GetCoverFromRetriever(retriever); return(new Song(title, album, artist, path, albumArtist, coverBitmap)); }
private byte[] GetImageSource(MediaMetadataRetriever retriever) { var bitmap = retriever.GetFrameAtTime(0); if (bitmap != null) { var stream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); byte[] bitmapData = stream.ToArray(); return(bitmapData); } return(null); }
public static Drawable GetSongPicture(string id) { MediaMetadataRetriever metadata = GetMetadata(id); byte[] pictureByteArray = metadata.GetEmbeddedPicture(); if (pictureByteArray != null) { return(new BitmapDrawable(Application.Context.Resources, BitmapFactory.DecodeByteArray(pictureByteArray, 0, pictureByteArray.Length))); } return(null); }
public static int GetMediaMetadataRetrieverPropertyInteger(Android.Net.Uri uri, int key, int defaultValue) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(uri.ToString()); string value = retriever.ExtractMetadata(key); if (value == null) { return(defaultValue); } return(int.Parse(value)); }
public AudioService() { _reader = new MediaMetadataRetriever(); if (Forms.Context != null) { _audioManager = (AudioManager)Forms.Context.GetSystemService(Context.AudioService); } _maxVolume = _audioManager.GetStreamMaxVolume(Stream.Music); CheckVolume(); CheckPosition(); }
public virtual async Task <IMediaItem> CreateMediaItem(IMediaItem mediaItem) { try { var metaRetriever = new MediaMetadataRetriever(); await metaRetriever.SetDataSourceAsync(mediaItem.MediaUri, RequestHeaders); mediaItem = await ExtractMediaInfo(metaRetriever, mediaItem); } catch (Exception) { } return(mediaItem); }