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;
        }
Esempio n. 2
0
        public static void updateRecordsData()
        {
            var newconn = GetConnection ("WingsRecorder");
            var m = newconn.Table<RecordingData> ().OrderByDescending(x=>x.ID).ToList ();

            var mycontresolv = MainActivity.mycontresol;

            foreach (var item in m) {

                var filename = item.filename;
                var myfile = new Java.IO.File (filename);
                if (myfile.Exists ()) {
                    item.isFileExist = true;

                    var mystrings = filename.Split (new String[]{ "_" }, StringSplitOptions.RemoveEmptyEntries);
                    var mynumber = string.Join ("", mystrings [mystrings.Length - 2].ToCharArray ().Where (Char.IsDigit));
                    item.contactNumber = mynumber;

                    var myuri = Android.Net.Uri.WithAppendedPath (ContactsContract.PhoneLookup.ContentFilterUri,
                                    Android.Net.Uri.Encode (mynumber));

                    using (var cursor = mycontresolv.Query (myuri, new string[]{ ContactsContract.Contacts.InterfaceConsts.DisplayName }, null, null, null)) {
                        if (cursor.MoveToFirst ()) {
                            item.contactName = cursor.GetString (cursor.GetColumnIndex (ContactsContract.Contacts.InterfaceConsts.DisplayName));
                        } else
                            item.contactName = item.contactNumber.ToString ();
                        cursor.Close ();
                    }

                    var my = new MediaMetadataRetriever ();
                    my.SetDataSource (filename);
                    var timerecd = my.ExtractMetadata (MetadataKey.Date);
                    if (timerecd != null) {
                        var timestrings = timerecd.Split (new String[]{ "." }, StringSplitOptions.RemoveEmptyEntries);
                        timestrings = timestrings [0].Split (new String[]{ "T" }, StringSplitOptions.RemoveEmptyEntries);
                        timerecd = timestrings [0] + timestrings [1];

                        item.callTime = DateTime.ParseExact (timerecd, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
                        item.Duration = Convert.ToInt32 (my.ExtractMetadata (MetadataKey.Duration));
                    }
                    if (filename.Contains ("_OUT"))
                        item.callType = "OUT";
                    else if (filename.Contains ("_IN"))
                        item.callType = "IN";

                    if (mynumber.Length > 7)
                        item.filteredContactNumber = mynumber.Substring (mynumber.Length - 8);
                    else
                        item.filteredContactNumber = mynumber;

                } else {
                    item.isFileExist = false;
                }
                newconn.Update (item);
            }
        }
Esempio n. 3
0
        private void createImages(HorizontalScrollView view)
        {
            MediaMetadataRetriever data = new MediaMetadataRetriever();
            data.SetDataSource(filename);
            int videoLength = Convert.ToInt32(data.ExtractMetadata(MetadataKey.Duration));
            #if DEBUG
            Console.WriteLine("Duration = {0}, videoLength = {1}", data.ExtractMetadata(MetadataKey.Duration), videoLength);
            #endif
            LinearLayout linLay = new LinearLayout(context);
            linLay.Orientation = Android.Widget.Orientation.Horizontal;
            linLay.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.FillParent);

            ShowLightboxDialog(Application.Resources.GetString(Resource.String.videoEditGenerateThumbs));
            ImageView imageView = new ImageView(context);
            imageView.LayoutParameters = new ViewGroup.LayoutParams((int)ImageHelper.convertDpToPixel(55f, context),
                                                                    (int)ImageHelper.convertDpToPixel(55f, context));

            #if DEBUG
            for (int n = 0; n < videoLength; ++n)
            {
                using (Bitmap bmp = data.GetFrameAtTime((long)n * 1000, (int)Option.ClosestSync))
                {
                    if (bmp != null)
                        Console.WriteLine("frame {0} contains an image", n);
                }
            }
            #endif

            for (int n = 10; n < /*videoLength*/timeUsed * fps; ++n)
            {
                using (Bitmap bmp = data.GetFrameAtTime((long)n, (int)Option.ClosestSync))
                {
                    if (bmp != null)
                    {
                        using (Bitmap smBmp = Bitmap.CreateScaledBitmap(bmp, (int)ImageHelper.convertDpToPixel(55f, context),
                                                                    (int)ImageHelper.convertDpToPixel(55f, context), true))
                        {
                            int m = new int();
                            m = n;
                            imageView.Tag = m;
                            imageView.Click += (object sender, EventArgs e) => frameClicked(sender, e);
                            imageView.SetImageBitmap(smBmp);
                        }
                    } else
                        imageView.SetBackgroundColor(Color.AliceBlue);
                }
                RunOnUiThread(() => linLay.AddView(imageView));
            }

            DismissLightboxDialog();
            data.Release();
        }
Esempio n. 4
0
        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);
        }
 private void SetMetadata(IMediaFile mediaFile, MediaMetadataRetriever retriever)
 {
     mediaFile.Metadata.Title = retriever?.ExtractMetadata(MetadataKey.Title) ?? "Unknown";
     mediaFile.Metadata.Artist = retriever?.ExtractMetadata(MetadataKey.Artist) ?? "Unknown";
     mediaFile.Metadata.Album = retriever?.ExtractMetadata(MetadataKey.Album);
 }
        /// <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());
        }
		/// <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);
            }
        }
Esempio n. 8
0
        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();
            }
        }
		public  MemoryStream CompressVideo( string sourceFilePath, string destinationFilePath, bool deleteSourceFile )
		{
			if (sourceFilePath == null || destinationFilePath == null)
				return null;

			MediaMetadataRetriever media = new MediaMetadataRetriever ();
			media.SetDataSource ( sourceFilePath );
			string videoRotation = media.ExtractMetadata ( MetadataKey.VideoRotation );


			XamarinAndroidFFmpeg.FFMpeg ffmpeg = new FFMpeg ( MainApplication.Context, App.DownloadsPath);
			var onComplete = new MyCommand ((_) => 
				{
					
				});

			var onMessage = new MyCommand ((message) => 
				{
					System.Diagnostics.Debug.WriteLine(  "---" + message);
				});


			if (videoRotation != null && videoRotation == "90")
			{
				string[] cmds = new string[] 
				{
					"-i",
					sourceFilePath,
					"-vcodec",
					"mpeg4",
					"-acodec",
					"aac",
					"-strict",
					"-2",
					"-ac",
					"1",
					"-ar",
					"16000",
					"-r",
					"13",
					"-ab",
					"32000",
					"-vf",
					"transpose=1",
					"-y",
					destinationFilePath
				};
				var callbacks = new FFMpegCallbacks (onComplete, onMessage);
				ffmpeg.Execute (cmds, callbacks);
			} 
			else 
			{
				string[] cmds = new string[] 
				{
					"-i",
					sourceFilePath,
					"-vcodec",
					"mpeg4",
					"-acodec",
					"aac",
					"-strict",
					"-2",
					"-ac",
					"1",
					"-ar",
					"16000",
					"-r",
					"13",
					"-ab",
					"32000",
					"-y",
					destinationFilePath
				};
				var callbacks = new FFMpegCallbacks (onComplete, onMessage);
				ffmpeg.Execute (cmds, callbacks);
			}
		

			if (deleteSourceFile) 
			{
				Java.IO.File toDel = new Java.IO.File ( sourceFilePath );
				toDel.Delete ();
			}


			MemoryStream ms = new MemoryStream();    
			FileStream file = new FileStream(  destinationFilePath, FileMode.Open, FileAccess.Read);
			file.CopyTo ( ms );
			file.Close();
			return ms;

		}
		public MemoryStream CreateVideoThumbnail ( string inputVideoPath, string outputImagePath )
		{

			MediaMetadataRetriever media = new MediaMetadataRetriever ();
			media.SetDataSource ( inputVideoPath );
			string videoRotation = media.ExtractMetadata ( MetadataKey.VideoRotation );

			XamarinAndroidFFmpeg.FFMpeg ffmpeg = new FFMpeg ( MainApplication.Context, App.DownloadsPath);
			var onComplete = new MyCommand ((_) => 
				{

				});

			var onMessage = new MyCommand ((message) => 
				{
					System.Diagnostics.Debug.WriteLine(  "---" + message);
				});

			var callbacks = new FFMpegCallbacks (onComplete, onMessage);

			if (videoRotation != null && videoRotation == "90") 
			{
				string[] cmds = new string[] {
					"-i",
					inputVideoPath,
					"-ss",
					"00:00:01.000",
					"-vf",
					"transpose=1",
					outputImagePath
				};
				ffmpeg.Execute (cmds, callbacks);
			} 
			else
			{
				string[] cmds = new string[]
				{
					"-i",
					inputVideoPath,
					"-ss",
					"00:00:01.000",
					outputImagePath
				};
				ffmpeg.Execute (cmds, callbacks);
			}

			MemoryStream ms = new MemoryStream ();
			FileStream stream = new FileStream (outputImagePath, FileMode.Open);
			stream.CopyTo (ms);
			return ms;

		}