Beispiel #1
0
		public async void PlaySound(Media media)
		{
			if (media == null || media.Data == null || media.Data.Length == 0)
				return;

			if (_soundPlayer != null) {
				_soundPlayer.Stop ();
				_soundPlayer.Reset ();
			} else {
				_soundPlayer = new MediaPlayer ();
			}

			try {
				// Open file and read from FileOffset FileSize bytes for the media
				using (Java.IO.RandomAccessFile file = new Java.IO.RandomAccessFile (media.FileName, "r")) {
					await _soundPlayer.SetDataSourceAsync(file.FD,media.FileOffset,media.FileSize);
					file.Close();
				}

				// Start media
				if (_soundPlayer != null) {
					_soundPlayer.Prepare();
					_soundPlayer.Start ();
				} else
					throw new InvalidCastException(String.Format ("Audio file format of media {0} is not valid", media.Name));
			} catch (Exception ex) {
				String s = ex.ToString();
			}
		}
 public ThumbnailOptions(IsolatedStorageFile isf, string filename, Media preferred, Media fallback, int minWidth)
 {
     IsoStoreFile = isf;
     Filename = filename;
     PreferedMedia = preferred;
     FallbackMedia = fallback;
     MinWidth = minWidth;
 }
 public ThumbnailOptions(IsolatedStorageFile isf, string filename, Media preferred, Media fallback, int minWidth, bool blur, int heightToCrop)
 {
     IsoStoreFile = isf;
     Filename = filename;
     PreferedMedia = preferred;
     FallbackMedia = fallback;
     MinWidth = minWidth;
     Blur = blur;
     CropRectangle = new Rectangle(0, 0, minWidth, heightToCrop);
 }
		/// <summary>
		/// Determines if a media represents a sound that can be played 
		/// by this SoundManager.
		/// </summary>
		/// <param name="media"></param>
		/// <returns>True if the sound type is supported by this sound 
		/// manager.</returns>
		public static bool IsPlayableSound(Media media)
		{
			if (media == null)
			{
				return false;
			}

			MediaType mt = media.Type;

			return mt == MediaType.MP3 || mt == MediaType.WAV || mt == MediaType.FDL;
		}
		public ScreenDialog (Input input) : base ()
		{
			this.input = input;
			this.text = input.Text;
			this.image = input.Image;
			if (input.InputType == InputType.Text)
				buttons.Add (Catalog.GetString("Ok"));
			if (input.InputType == InputType.MultipleChoice)
				foreach (string s in input.Choices)
					buttons.Add (s);
		}
		public ScreenDialog (MessageBox msgBox) : base ()
		{
			this.msgBox = msgBox;
			this.text = msgBox.Text;
			this.image = msgBox.Image;
			if (!String.IsNullOrWhiteSpace (msgBox.FirstButtonLabel)) {
				this.buttons.Add (msgBox.FirstButtonLabel);
				if (!String.IsNullOrWhiteSpace (msgBox.SecondButtonLabel))
					this.buttons.Add (msgBox.SecondButtonLabel);
			}

			// OS specific details
			if (new Version (UIDevice.CurrentDevice.SystemVersion) >= new Version(7,0)) 
			{
				// Code that uses features from Xamarin.iOS 7.0
				this.EdgesForExtendedLayout = UIRectEdge.None;
			}
		}
Beispiel #7
0
		public void PlaySound(Media media)
		{
			NSError error;

			if (_soundPlayer != null) {
				_soundPlayer.Stop();
				_soundPlayer = null;
			}

			if (media == null || media.Data == null || media.Data.Length == 0)
				return;

			try {
				_soundPlayer = AVAudioPlayer.FromData(NSData.FromArray (media.Data), out error);
			}
			catch (Exception e) {
			}

			if (_soundPlayer != null)
				_soundPlayer.Play ();
//			else
//				throw new InvalidCastException(String.Format ("Audio file format of media {0} is not valid",media.Name));
		}
		private string GetCachePathCore(Media media)
		{
			return GetCachePathCore(String.Format("{0}.{1}", media.MediaId, media.Type.ToString()));
		}
		/// <summary>
		/// Gets the path to the cached version of a media.
		/// </summary>
		/// <param name="media"></param>
		/// <returns>The isostore path of the media if it is cached, null otherwise.</returns>
		public string GetCachePath(Media media)
		{
			string filename = GetCachePathCore(media);

			using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
			{
				return isf.FileExists(filename) ? filename : null;
			}
		}
		public static ImageSource SaveThumbnail(IsolatedStorageFile isoStore, string filename, Media prefered, Media fallback = null, int minWidth = -1)
		{
			// Make sure this method runs in the UI thread.
			if (!Deployment.Current.Dispatcher.CheckAccess())
			{
				return Deployment.Current.Dispatcher.Invoke<ImageSource>(() => 
				{
					return SaveThumbnail(isoStore, filename, prefered, fallback, minWidth);
				});
			}
			
			// Gets the images.
			BitmapSource preferedImage = GetBitmapSource(prefered);
			BitmapSource fallbackImage = GetBitmapSource(fallback);

			// Determines which image needs to be saved.
			BitmapSource targetImage = preferedImage;
			if (preferedImage == null)
			{
				// Use the fallback image if the prefered image does not exist.
				targetImage = fallbackImage;
			}
			else if (fallbackImage != null && minWidth > -1 && preferedImage.PixelWidth < minWidth && preferedImage.PixelWidth < fallbackImage.PixelWidth)
			{
				// Use the fallback image if its width is bigger than the prefered image's width, the latter being
				// smaller than the min width.
				targetImage = fallbackImage;
			}

			// No image? Return.
			if (targetImage == null)
			{
				return null; 
			}

			// Gets the dimensions of the target image.
			int targetWidth = (int) Math.Max(minWidth, targetImage.PixelWidth);
			double sourcePixelRatio = targetImage.PixelWidth / (double) targetImage.PixelHeight;
			int targetHeight = (int) Math.Floor(targetWidth / sourcePixelRatio);
			
			// Saves the image.
			using (IsolatedStorageFileStream stream = isoStore.OpenFile(filename, FileMode.Create))
			{
				new WriteableBitmap(targetImage).SaveJpeg(stream, targetWidth, targetHeight, 0, 100);
			}

			// Returns the image.
			return targetImage;
		}
		public void StartSound(Media media)
		{
			NSError error;
			if (soundPlayer != null) {
				soundPlayer.Stop();
				soundPlayer = null;
			}
			soundPlayer = AVAudioPlayer.FromData(NSData.FromArray (media.Data), out error);
			if (soundPlayer != null)
				soundPlayer.Play ();
			else
				logMessage (LogLevel.Error,String.Format ("Audio file format of media {0} is not valid",media.Name));
		}
		private string GetCachePathCore(Media media)
		{
			// FDL files are converted to WAV files.
			string extension = media.Type == MediaType.FDL ? "WAV" : media.Type.ToString().ToUpper();

			return GetCachePathCore(String.Format("{0}.{1}", media.MediaId, extension));
		}
		/// <summary>
		/// Plays a media sound.
		/// </summary>
		/// <param name="media">The sound to play.</param>
		public void PlayMediaSound(Media media)
		{
			// Sanity check.
			if (!SoundManager.IsPlayableSound(media))
			{
				System.Diagnostics.Debug.WriteLine("AppViewModel: Ignored playing sound of unsupported type: " + media.Type.ToString());
				return;
			}
			
			// Gets the media filename in cache.
			CartridgeTag tag = Model.CartridgeStore.GetCartridgeTagOrDefault(Model.Core.Cartridge);
			string filename = tag.GetMediaCachePath(media, true);

			// Plays the file.
			SoundManager.PlaySound(filename);
		}
		public Bitmap ConvertMediaToBitmap(Media media, int maxWidth = -1)
		{
			Bitmap result = BitmapFactory.DecodeByteArray (media.Data, 0, media.Data.Length);

			// We need to adjust the height if the width of the bitmap is
			// smaller than the view width, otherwise the image will be boxed.
			if (result.Width > 0) {
				var metrics = Resources.DisplayMetrics;
				int width = (int)(result.Width * metrics.Density);
				int height = (int)(result.Height * metrics.Density);

				maxWidth = maxWidth < 0 ? (int)(metrics.WidthPixels - 2 * Resources.GetDimension(Resource.Dimension.screen_frame)) : maxWidth;
				int maxHeight = (int)(0.5 * metrics.HeightPixels);

				if (width > maxWidth) {
					double factor = (double)maxWidth / (double)width;
					width = maxWidth;
					height = (int)(height * factor);
				}

				if (height > maxHeight) {
					double factor = (double)maxHeight / (double)height;
					height = maxHeight;
					width = (int)(width * factor);
				}

				result = Bitmap.CreateScaledBitmap(result, width, height, true);
			}
			return result;
		}
		private void ConvertAndWriteFDL(IsolatedStorageFileStream fs, Media sound)
		{
			using (MemoryStream inputFdlStream = new MemoryStream(sound.Data))
			{
				using (Stream outputWavStream = new WF.Player.Core.Formats.FDL().ConvertToWav(inputFdlStream))
				{
					outputWavStream.CopyTo(fs);
				}
			}
		}
		public static WriteableBitmap GetBitmapSource(Media media)
		{
			if (media == null || media.Data == null)
			{
				return null;
			}

			return GetBitmapSource(media.Data);
		}
		public Bitmap ConvertMediaToBitmap(Media media, int maxWidth = -1)
		{
			Bitmap result = null;

			// First get dimensions of the image
			BitmapFactory.Options options = new BitmapFactory.Options();   

			// First decode with InJustDecodeBounds=true to check dimensions
			options.InJustDecodeBounds = true;
			BitmapFactory.DecodeByteArray(media.Data, 0, media.Data.Length, options);

			// Calculate inSampleSize

			// We need to adjust the height if the width of the bitmap is
			// smaller than the view width, otherwise the image will be boxed.
			if (options.OutWidth > 0) {

				var metrics = Resources.DisplayMetrics;
				int width = (int)(options.OutWidth * 1); //metrics.Density);
				int height = (int)(options.OutHeight * 1); //metrics.Density);
							
				maxWidth = maxWidth < 0 ? (int)(metrics.WidthPixels - 2 * Resources.GetDimension(Resource.Dimension.screen_frame)) : maxWidth;
				int maxHeight = (int)(0.5 * metrics.HeightPixels);
							
				if (width > maxWidth && (Main.Prefs.ImageResize == ImageResize.ResizeWidth || Main.Prefs.ImageResize == ImageResize.ShrinkWidth)) {
					double factor = (double)maxWidth / (double)width;
					width = maxWidth;
					height = (int)(height * factor);
					}

				if (width < maxWidth && Main.Prefs.ImageResize == ImageResize.ResizeWidth) {
					double factor = (double)maxWidth / (double)width;
					width = maxWidth;
					height = (int)(height * factor);
				}

				if (height != maxHeight && Main.Prefs.ImageResize == ImageResize.ResizeHeight) {
					double factor = (double)maxHeight / (double)height;
					height = maxHeight;
					width = (int)(width * factor);
				}

				//	result = Bitmap.CreateScaledBitmap(bitmap, width, height, true);
				if (options.OutWidth > width || options.OutHeight > height) {
					// Calculate ratios of height and width to requested height and width
					int heightRatio = Convert.ToInt32(Math.Round((double) options.OutHeight / (double) height));
					int widthRatio = Convert.ToInt32(Math.Round((double) options.OutWidth / (double) width));

					// Choose the smallest ratio as inSampleSize value, this will guarantee
					// a final image with both dimensions larger than or equal to the
					// requested height and width.
					options.InSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
				} else {
					options.InSampleSize = 1;
				}

				// Decode bitmap with InSampleSize set
				options.InJustDecodeBounds = false;        


				if (options.OutWidth == width && options.OutHeight == height) {
					// Cave: If width and height is the same, CreateScaledBitmap returns the same bitmap, not a new one :(
					result = BitmapFactory.DecodeByteArray (media.Data, 0, media.Data.Length, options); 
				} else {
					using (Bitmap bm = BitmapFactory.DecodeByteArray (media.Data, 0, media.Data.Length, options)) { 
						result = Bitmap.CreateScaledBitmap(bm, width, height, true);
					}
				}
			}

			return result;
		}
Beispiel #18
0
		/// <summary>
		/// Create HTML from plain text and media.
		/// </summary>
		/// <returns>Text converted to HTML.</returns>
		/// <param name="text">Original text.</param>
		/// <param name="media">Media object.</param>
		public static string FromText(string text, TextAlignment textAlignment, Media media = null, int fontSize = -1)
		{
			if (text == null)
			{
				return string.Empty;
			}

			var html = text.Replace("<", "&lt;").Replace(">", "&gt;").Replace("\n", "<br>");

			// Add style to html code
			#if __IOS__

			if (fontSize == -1)
			{
				fontSize = Settings.FontSize;
			}

			html = "<style>" + DefaultStyle + "</style>" + html;

			// Replace default values
			html = html.Replace("-Font0-", ((int)(fontSize * 0.9)).ToString());
			html = html.Replace("-Font1-", ((int)(fontSize * 1.0)).ToString());
			html = html.Replace("-Font2-", ((int)(fontSize * 1.2)).ToString());
			html = html.Replace("-Font3-", ((int)(fontSize * 1.4)).ToString());
			html = html.Replace("-Font4-", ((int)(fontSize * 1.8)).ToString());
			html = html.Replace("-Font5-", ((int)(fontSize * 2.0)).ToString());
			html = html.Replace("-TextAlign-", AlignmentToString(textAlignment));
			html = html.Replace("-TextColor-", ColorToHTML(App.Colors.Text));
			html = html.Replace("-BackgroundColor-", ColorToHTML(App.Colors.Background));

			#endif

			return html;
		}
		/// <summary>
		/// Gets the path to the cached version of a media.
		/// </summary>
		/// <param name="media"></param>
		/// <param name="recacheIfFileNotFound">If true, the cache for this media
		/// is recreated if its theoretical file path was not found. If false,
		/// null is returned if </param>
		/// <returns>The isostore path of the media if it is cached, null otherwise.</returns>
		public string GetMediaCachePath(Media media, bool recacheIfFileNotFound)
		{
			// Looks the file up in the registered sounds.
			// If not found, gets the theoretical value instead.
			string filename;
			if (!_soundFiles.TryGetValue(media.MediaId, out filename))
			{
				filename = GetCachePathCore(media);
			}

			// Recreates the file if it doesn't exist.
			using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
			{
				if (!isf.FileExists(filename))
				{
					// Makes sure the directory exists.
					isf.CreateDirectory(System.IO.Path.GetDirectoryName(filename));

					// Writes the contents of the media.
					using (IsolatedStorageFileStream fs = isf.OpenFile(filename, FileMode.Create, FileAccess.Write))
					{
						fs.Write(media.Data, 0, media.Data.Length);
					}
				}
			}

			// Updates the path in the sounds dictionary.
			_soundFiles[media.MediaId] = filename;

			return filename;
		}
Beispiel #20
0
		/// <summary>
		/// Creates a message box descriptor.
		/// </summary>
		/// <param name="text">Text to display.</param>
		/// <param name="mediaObj">Media object to display (can be null.)</param>
		/// <param name="btn1label">Label of the first button (if null or empty, a default value will be used.)</param>
		/// <param name="btn2label">Label of the second button (if null or empty, the button will not be shown.)</param>
		/// <param name="callback">Function to call once the message box has gotten a result.</param>
		public MessageBox(string text, Media mediaObj, string btn1label, string btn2label, Action<string> cb)
		{
			Text = text.ReplaceHTMLMarkup();
			Image = mediaObj;
			FirstButtonLabel = String.IsNullOrEmpty(btn1label) ? null : btn1label;
			SecondButtonLabel = String.IsNullOrEmpty(btn2label) ? null : btn2label;

			_callback = cb;
		} 
Beispiel #21
0
		/// <summary>
		/// Create HTML froms markdown text and media.
		/// </summary>
		/// <returns>Markdown converted to HTML.</returns>
		/// <param name="markdown">Text with markdown.</param>
		/// <param name="media">Media object.</param>
		public static string FromMarkdown(string markdown, TextAlignment textAlignment, Media media = null, int fontSize = -1)
		{
//			markdown.Replace("<", "&lt;").Replace(">", "&gt;").Replace("\n", "<br>");

			// Because markdown interpretes linebreaks in a different way
			var html = markdownConverter.Transform(markdown.Replace("\n", "  \n"));

			// Add style to html code
			#if __IOS__

			if (fontSize == -1)
			{
				fontSize = Settings.FontSize;
			}

			html = "<style>" + DefaultStyle + "</style>" + html;

			// Replace default values
			html = html.Replace("-Font0-", ((int)(fontSize * 0.9)).ToString());
			html = html.Replace("-Font1-", ((int)(fontSize * 1.0)).ToString());
			html = html.Replace("-Font2-", ((int)(fontSize * 1.2)).ToString());
			html = html.Replace("-Font3-", ((int)(fontSize * 1.4)).ToString());
			html = html.Replace("-Font4-", ((int)(fontSize * 1.8)).ToString());
			html = html.Replace("-Font5-", ((int)(fontSize * 2.0)).ToString());
			html = html.Replace("-TextAlign-", AlignmentToString(textAlignment));
			html = html.Replace("-TextColor-", ColorToHTML(App.Colors.Text));
			html = html.Replace("-BackgroundColor-", ColorToHTML(App.Colors.Background));

			#endif

			return html;
		}
		/// <summary>
		/// Plaies a media sound file.
		/// </summary>
		/// <param name="media">Media.</param>
		private async void PlayMedia (Media media)
		{
			try {
				// Reset MediaPlayer to be ready for the next sound
				mediaPlayer.Reset();

				// Open file and read from FileOffset FileSize bytes for the media
				using (Java.IO.RandomAccessFile file = new Java.IO.RandomAccessFile(media.FileName,"r")) {
					await mediaPlayer.SetDataSourceAsync(file.FD,media.FileOffset,media.FileSize);
					file.Close();
				}

				// Start media
				mediaPlayer.Prepare();
				mediaPlayer.Start();
			} catch (Exception ex) {
				String s = ex.ToString();
			}
		}
Beispiel #23
0
		/// <summary>
		/// Converts the string to HTML and add decoration.
		/// </summary>
		/// <returns>String converted and docorated as HTML.</returns>
		/// <param name="text">Text to convert.</param>
		/// <param name="media">Media object.</param>
		public static string ConvertStringToHTML(string text, TextAlignment textAlignment, Media media = null)
		{
			var code = new StringBuilder();
			return text;
			code.Append("<html>");
			code.Append("<head>");
			code.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, miniumum-scale=0.5, maximum-scale=40.0\"/>");
			code.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">");
			code.Append("<style>");
			code.Append("html {");
			code.AppendFormat("	background-color: #{0};", ColorToHTML(App.Colors.Background));
			code.Append("	padding: 2px;");
			code.Append("	margin: 0px;");
			code.Append("}");
			code.Append("body {");
			code.AppendFormat("	color: #{0};", ColorToHTML(App.Colors.Text));
			code.AppendFormat("	background-color: #{0};", ColorToHTML(App.Colors.Background));
			code.Append("	font-family: sans-serif;");
			code.AppendFormat("	font-size: {0}px;", Settings.FontSize);
			code.Append("}");
			code.Append("img{");

			switch (Settings.ImageResize)
			{
				case ImageResize.NoResize:
					break;
				case ImageResize.ShrinkWidth:
					code.Append("	max-width:100%;");
					break;
				case ImageResize.ResizeWidth:
					code.Append("	width:100%;");
					break;
				case ImageResize.ResizeHeight:
					code.Append("	max-height:50%;");
					break;
			}

			code.Append("}");
			code.Append("</style>");
			code.Append("</head>");
			code.Append("<body>");

			// If there is a media, insert it
			if (media != null)
			{
				code.AppendFormat("<div align=\"{0}\">", AlignmentToString(Settings.ImageAlignment));
				code.Append("<img src=\"data:;base64," + System.Convert.ToBase64String(media.Data) + "\">");
				code.Append("</div>");
			}

			// Are media and text visible, than separate with a newline
			if (media != null && !string.IsNullOrEmpty(text))
			{
				code.Append("<br>");
			}

			// If there is text, insert it
			if (!string.IsNullOrEmpty(text))
			{
				code.AppendFormat("<div align=\"{0}\">", AlignmentToString(textAlignment));
				code.Append(text.Replace("<", "&lt;").Replace(">", "&gt;").Replace("\n", "<br>"));
			}

			code.Append("</div>");
			code.Append("</body>");
			code.Append("</html>");

			return code.ToString();
		}
Beispiel #24
0
		/// <summary>
		/// Gets the cached image source for media.
		/// </summary>
		/// <returns>The image source for media.</returns>
		/// <param name="media">Media to use.</param>
		public ImageSource GetImageSourceForMedia(Media media)
		{
			ImageSource imageSource;

			if (media == null || media.Data == null)
			{
				return this.imageSourceEmptyIcon;
			}

			if (!imageSources.TryGetValue(media.MediaId, out imageSource))
			{
				// Didn't find ImageSource, so create a new one
				imageSource = ImageSource.FromStream(() => media.Data != null ? new MemoryStream(media.Data) : null);

				// And save it in the cache for later use 
				imageSources.Add(media.MediaId, imageSource);
			}

			// Found ImageSource
			return imageSource;
		}
		/// <summary>
		/// Plays a media sound.
		/// </summary>
		/// <param name="media">The sound to play.</param>
		public void PlayMediaSound(Media media)
		{
			// Gets the media filename in cache.
			CartridgeTag tag = Model.CartridgeStore.GetCartridgeTag(Model.Core.Cartridge);
			string filename = tag.GetCachePath(media);

			// Plays the file.
			SoundManager.PlaySound(filename);
		}