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; }
/// <summary> /// Intializes the player. /// </summary> public async Task Play () { if (mediaPlayer != null && MediaPlayerState == PlaybackStateCompat.StatePaused) { //We are simply paused so just start again mediaPlayer.Start (); UpdatePlaybackState(PlaybackStateCompat.StatePlaying); StartNotification (); //Update the metadata now that we are playing UpdateMediaMetadataCompat (); return; } if (mediaPlayer == null) InitializePlayer (); if(mediaSessionCompat == null) InitMediaSession (); if (mediaPlayer.IsPlaying) { UpdatePlaybackState(PlaybackStateCompat.StatePlaying); return; } try { MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever (); await mediaPlayer.SetDataSourceAsync (ApplicationContext, Android.Net.Uri.Parse (audioUrl)); await metaRetriever.SetDataSourceAsync(audioUrl, new Dictionary<string,string>()); var focusResult = audioManager.RequestAudioFocus (this, Stream.Music, AudioFocus.Gain); if (focusResult != AudioFocusRequest.Granted) { //could not get audio focus Console.WriteLine("Could not get audio focus"); } UpdatePlaybackState(PlaybackStateCompat.StateBuffering); mediaPlayer.PrepareAsync (); AquireWifiLock (); UpdateMediaMetadataCompat (metaRetriever); StartNotification (); byte[] imageByteArray = metaRetriever.GetEmbeddedPicture (); if (imageByteArray == null) Cover = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.album_art); else Cover = await BitmapFactory.DecodeByteArrayAsync (imageByteArray, 0, imageByteArray.Length); } catch (Exception ex) { UpdatePlaybackState(PlaybackStateCompat.StateStopped); mediaPlayer.Reset(); mediaPlayer.Release(); mediaPlayer = null; //unable to start playback log error Console.WriteLine(ex); } }
async Task <FileData> GetFileData(Android.Net.Uri p_uri) { var filePath = IOUtil.GetPath(_context, p_uri); if (string.IsNullOrEmpty(filePath)) { filePath = IOUtil.IsMediaStore(p_uri.Scheme) ? p_uri.ToString() : p_uri.Path; } var fileName = GetFileName(_context, p_uri); var fd = new FileData(filePath, fileName, (ulong)new File(filePath).Length()); string ext = fd.Ext; // 生成文件描述和缩略图 if (FileFilter.UwpImage.Contains(ext)) { BitmapFactory.Options options = new BitmapFactory.Options(); // 只解析图片大小,不加载内容 options.InJustDecodeBounds = true; BitmapFactory.DecodeFile(filePath, options); fd.Desc = $"{options.OutWidth} x {options.OutHeight} ({ext.TrimStart('.')})"; int maxSize = Math.Max(options.OutWidth, options.OutHeight); if (maxSize > FileData.ThumbSize) { // 直接按缩放比例加载 options.InJustDecodeBounds = false; options.InSampleSize = maxSize / FileData.ThumbSize; // v29 弃用 //options.InPurgeable = true; Bitmap bmp = BitmapFactory.DecodeFile(filePath, options); fd.ThumbPath = System.IO.Path.Combine(Kit.CachePath, Kit.NewGuid + "-t.jpg"); using (var fs = System.IO.File.Create(fd.ThumbPath)) { await bmp.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fs); } bmp.Recycle(); } } else if (FileFilter.UwpVideo.Contains(ext)) { Android.Media.MediaMetadataRetriever media = new Android.Media.MediaMetadataRetriever(); try { await media.SetDataSourceAsync(filePath); string dur = media.ExtractMetadata(Android.Media.MetadataKey.Duration); string width = media.ExtractMetadata(Android.Media.MetadataKey.VideoWidth); string height = media.ExtractMetadata(Android.Media.MetadataKey.VideoHeight); fd.Desc = string.Format("{0:HH:mm:ss} ({1} x {2})", new DateTime(long.Parse(dur) * 10000), width, height); } catch { } finally { media.Release(); } // 帧缩略图 var bmp = await ThumbnailUtils.CreateVideoThumbnailAsync(filePath, ThumbnailKind.MiniKind); fd.ThumbPath = System.IO.Path.Combine(Kit.CachePath, Kit.NewGuid + "-t.jpg"); using (var fs = System.IO.File.Create(fd.ThumbPath)) { await bmp.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fs); } bmp.Recycle(); } else if (FileFilter.UwpAudio.Contains(ext)) { Android.Media.MediaMetadataRetriever media = new Android.Media.MediaMetadataRetriever(); try { await media.SetDataSourceAsync(filePath); string dur = media.ExtractMetadata(Android.Media.MetadataKey.Duration); fd.Desc = string.Format("{0:mm:ss}", new DateTime(long.Parse(dur) * 10000)); } catch { } finally { media.Release(); } } return(fd); }
protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode != Result.Ok) { if (!string.IsNullOrEmpty(_path) && File.Exists(_path)) { try { File.Delete(_path); } catch { } } OnCaptured(null); Finish(); return; } try { FileData fd = new FileData(_path, System.IO.Path.GetFileName(_path), (ulong)new Java.IO.File(_path).Length()); string ext = fd.Ext; // 生成文件描述和缩略图 if (ext == ".jpg") { BitmapFactory.Options options = new BitmapFactory.Options(); // 只解析图片大小,不加载内容 options.InJustDecodeBounds = true; BitmapFactory.DecodeFile(_path, options); fd.Desc = $"{options.OutWidth} x {options.OutHeight} ({ext.TrimStart('.')})"; int maxSize = Math.Max(options.OutWidth, options.OutHeight); if (maxSize > FileData.ThumbSize) { // 直接按缩放比例加载 options.InJustDecodeBounds = false; options.InSampleSize = maxSize / FileData.ThumbSize; // v29 弃用 //options.InPurgeable = true; Bitmap bmp = BitmapFactory.DecodeFile(_path, options); fd.ThumbPath = System.IO.Path.Combine(Kit.CachePath, Kit.NewGuid + "-t.jpg"); using (var fs = System.IO.File.Create(fd.ThumbPath)) { await bmp.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fs); } bmp.Recycle(); } } else if (ext == ".mp4") { Android.Media.MediaMetadataRetriever media = new Android.Media.MediaMetadataRetriever(); try { await media.SetDataSourceAsync(_path); string dur = media.ExtractMetadata(Android.Media.MetadataKey.Duration); string width = media.ExtractMetadata(Android.Media.MetadataKey.VideoWidth); string height = media.ExtractMetadata(Android.Media.MetadataKey.VideoHeight); fd.Desc = string.Format("{0:HH:mm:ss} ({1} x {2})", new DateTime(long.Parse(dur) * 10000), width, height); } catch { } finally { media.Release(); } // 帧缩略图 var bmp = await ThumbnailUtils.CreateVideoThumbnailAsync(_path, ThumbnailKind.MiniKind); fd.ThumbPath = System.IO.Path.Combine(Kit.CachePath, Kit.NewGuid + "-t.jpg"); using (var fs = System.IO.File.Create(fd.ThumbPath)) { await bmp.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fs); } bmp.Recycle(); } OnCaptured(fd); } catch { OnCaptured(null); } finally { Finish(); } }