audio pause in xamarin.forms C# - audio

So i am building an app using xamarin.forms which needs to play and control audio. I have currently got my audio file playing on both android and iOS BUT I can't get other controls to work such as .Pause() and .Stop()
Playing audio works in both examples.
I thank you in advance!
Here is my code for each platform
ANDROID:
using System;
using Xamarin.Forms;
using AudioPlayEx.Droid;
using AudioToolbox;
using Android.Media;
using Android.Content.Res;
using Android.OS;
using Android;
[assembly: Dependency(typeof(AudioService))]
namespace AudioPlayEx.Droid
{
public class AudioService : IAudio
{
public AudioService()
{
}
MediaPlayer player;
public void PlayAudioFile(string fileName)
{
var player = new MediaPlayer();
var fd = Android.App.Application.Context.Assets.OpenFd(fileName);
player.Prepared += (s, e) =>
{
player.Start();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
}
protected MediaPlayer playme;
public void PauseAudioFile(String fileName)
{
var player = new MediaPlayer();
var fd = Android.App.Application.Context.Assets.OpenFd(fileName);
player.Prepared += (s, e) =>
{
player.Pause();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
}
}
}
iOS:
using System;
using Xamarin.Forms;
using AudioPlayEx;
using AudioPlayEx.iOS;
using System.IO;
using Foundation;
using AVFoundation;
[assembly: Dependency(typeof(AudioService))]
namespace AudioPlayEx.iOS
{
public class AudioService : IAudio
{
public AudioService()
{
}
public void PlayAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
_player = null;
};
_player.Play();
}
public void PauseAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.Pause();
}
}
}

I think you need to save your instance of AVAudioPlayer to a variable and call pause on that object. Right now you're creating a new AVAudioPlayer and calling pause on it, which is doing nothing. I've added iOS code to show what I mean. Android should be similar.
iOS:
public class AudioService : IAudio
{
AVAudioPlayer _player;
public void PlayAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
var url = NSUrl.FromString(sFilePath);
_player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
_player = null;
};
_player.Play();
}
public void PauseAudioFile(string fileName)
{
_player.Pause();
}
}

That topic is old, but I did it that way:
MediaPlayer player;
public void PlayAudioFile(string fileName, string ONOF)
{
if (ONOF == "OFF")
{
player.Stop();
}
if (ONOF == "ON")
{
player = new MediaPlayer();
var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName);
player.Prepared += (s, e) =>
{
player.Start();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
}
}

Related

How do I implement iOS "shake to undo" in Xamarin Forms, only on apple devices?

This blog describes how to perform shake to undo, however I'd like to create some kind of base class (in Xamarin forms) that I can reuse this code:
#region respond to shaking (OS3+)
public override bool CanBecomeFirstResponder {
get {
return true;
}
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
this.BecomeFirstResponder();
}
public override void ViewWillDisappear (bool animated)
{
this.ResignFirstResponder();
base.ViewWillDisappear (animated);
}
public override void MotionEnded (UIEventSubtype motion, UIEvent evt)
{
Console.WriteLine("Motion detected");
if (motion == UIEventSubtype.MotionShake)
{
Console.WriteLine("and was a shake");
// Do your application-specific shake response here...
Update();
}
}
#endregion
I'm not sure where to begin... to create a base class that only applies to iOS.
Is there any kind of Dependency injection I can use with XamarinForms for this runtime implementation of a base class for all views?
Explaination
The good news is we can take advantage of the Device Motion NuGet Package in lieu of Custom Renderers!
We can implement the shake functionality in a base NavgiationPage class and use this as our MainPage.
I've also included logic in the App constructor that only implements the ShakeListenerNavigationPage for iOS.
Code
using System;
using System.Diagnostics;
using Xamarin.Forms;
using DeviceMotion.Plugin;
using DeviceMotion.Plugin.Abstractions;
namespace YourNamespace
{
public class App : Application
{
public App()
{
NavigationPage navigationPage;
switch(Device.RuntimePlatform)
{
case Device.iOS:
navigationPage = new ShakeListenerNavigationPage(new MyPage());
break;
default:
navigationPage = new NavigationPage(new MyPage());
break;
}
MainPage = navigationPage;
}
}
public class ShakeListenerNavigationPage : NavigationPage
{
#region Constant Fields
const int _shakeDetectionTimeLapse = 250;
readonly double _shakeThreshold;
#endregion
#region Fields
bool _hasUpdated;
DateTime _lastUpdate;
double _lastX, _lastY, _lastZ;
#endregion
#region Constructors
public ShakeListenerNavigationPage(Page root) : base(root)
{
switch (Device.RuntimePlatform)
{
case Device.iOS:
_shakeThreshold = 20;
break;
default:
_shakeThreshold = 800;
break;
}
CrossDeviceMotion.Current.Start(MotionSensorType.Accelerometer, MotionSensorDelay.Default);
CrossDeviceMotion.Current.SensorValueChanged += HandleSensorValueChanged;
}
#endregion
#region Methods
void HandleSensorValueChanged(object sender, SensorValueChangedEventArgs e)
{
if (e.SensorType == MotionSensorType.Accelerometer)
{
double x = ((MotionVector)e.Value).X;
double y = ((MotionVector)e.Value).Y;
double z = ((MotionVector)e.Value).Z;
var currentTime = DateTime.Now;
if (_hasUpdated == false)
{
_hasUpdated = true;
_lastUpdate = currentTime;
}
else
{
var hasMinimumTimeElapsed = (currentTime - _lastUpdate).TotalMilliseconds > _shakeDetectionTimeLapse;
if (!hasMinimumTimeElapsed)
return;
_lastUpdate = currentTime;
var timeSinceLastShakeInMilliseconds = (currentTime - _lastUpdate).TotalMilliseconds;
var totalMovementDistance = x + y + z - _lastX - _lastY - _lastZ;
var shakeSpeed = Math.Abs(totalMovementDistance) / timeSinceLastShakeInMilliseconds * 10000;
Debug.WriteLine($"Shake Speed: {shakeSpeed}");
if (shakeSpeed > _shakeThreshold)
HandleShake();
}
_lastX = x;
_lastY = y;
_lastZ = z;
}
}
void HandleShake()
{
Device.BeginInvokeOnMainThread(async () => await DisplayAlert("Shake Detected", "You shook your device!", "Ok"));
}
#endregion
}
}
Sample App
Here's a sample Xamarin.Forms app where I implemented this feature!
https://github.com/brminnick/InvestmentDataSampleApp

Azure Notification Hub - Android app crashing when receive notification

I'm using Azure Notification Hub with Firebase Cloud Messaging and Xamarin. When I have the app in the background or in use, I can receive notifications. But when I kill the app from the Android current app list, I'm able to receive one notification but after that, I have the error "my_app stopped (close the application)". Any idea why ? I don't have error log because it happens when the app is killed.
This is my code, from the documentation
using System;
using System.Collections.Generic;
using System.Text;
using Android.App;
using Android.Content;
using Android.Util;
using WindowsAzure.Messaging;
using Gcm.Client;
[assembly: Permission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name ="com.google.android.c2dm.permission.RECEIVE")]
//GET_ACCOUNTS is needed only for Android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace Waka.Droid
{
[BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE },
Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
Categories = new string[] { "#PACKAGE_NAME#" })]
public class MyBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
{
public static string[] SENDER_IDS = new string[] { Constants.SenderID };
public const string TAG = "MyBroadcastReceiver-GCM";
}
[Service] // Must use the service tag
public class PushHandlerService : GcmServiceBase
{
public static string RegistrationID { get; private set; }
private NotificationHub Hub { get; set; }
public PushHandlerService() : base(Constants.SenderID)
{
}
protected override void OnRegistered(Context context, string registrationId)
{
RegistrationID = registrationId;
Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString,
context);
try
{
Hub.UnregisterAll(registrationId);
}
catch (Exception ex)
{
Log.Error(MyBroadcastReceiver.TAG, ex.Message);
}
//var tags = new List<string>() { "falcons" }; // create tags if you want
var tags = new List<string>() { };
try
{
var hubRegistration = Hub.Register(registrationId, tags.ToArray());
}
catch (Exception ex)
{
Log.Error(MyBroadcastReceiver.TAG, ex.Message);
}
}
protected override void OnMessage(Context context, Intent intent)
{
var msg = new StringBuilder();
if (intent != null && intent.Extras != null)
{
foreach (var key in intent.Extras.KeySet())
msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
}
string messageText = intent.Extras.GetString("message");
if (!string.IsNullOrEmpty(messageText))
{
createNotification("Shotgun!", messageText);
}
else
{
createNotification("Undefined", msg.ToString());
}
}
void createNotification(string title, string desc)
{
//Create notification
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
//Create an intent to show UI
var uiIntent = new Intent(this, typeof(MainActivity));
PendingIntent resultPendingIntent =
PendingIntent.GetActivity(
this,
0,
uiIntent,
0
);
Notification noti = new Notification.Builder(this)
.SetContentTitle("" + title)
.SetContentText(desc)
.SetSmallIcon(Android.Resource.Drawable.SymActionEmail)
.SetContentIntent(resultPendingIntent)
.SetDefaults(NotificationDefaults.All)
.Build();
//Show the notification
notificationManager.Notify(1, noti);
dialogNotify(title, desc);
}
protected void dialogNotify(String title, String message)
{
MainActivity.instance.RunOnUiThread(() =>
{
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.instance);
AlertDialog alert = dlg.Create();
alert.SetTitle(title);
alert.SetButton("Ok", delegate
{
alert.Dismiss();
});
alert.SetMessage(message);
alert.Show();
});
}
protected override void OnUnRegistered(Context context, string registrationId)
{
}
protected override bool OnRecoverableError(Context context, string errorId)
{
return base.OnRecoverableError(context, errorId);
}
protected override void OnError(Context context, string errorId)
{
}
}
}
MainActivity.cs:
using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Util;
using Gcm.Client;
namespace Waka.Droid
{
[Activity(Label = "Waka.Droid", Icon = "#drawable/icon", Theme = "#style/MyTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static MainActivity instance;
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
instance = this;
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
RegisterWithGCM();
}
private void RegisterWithGCM()
{
// Check to ensure everything's set up right
GcmClient.CheckDevice(this);
GcmClient.CheckManifest(this);
// Register for push notifications
GcmClient.Register(this, Constants.SenderID);
}
}
}

Xamarin Forms adding a placeholder to an Editor for iOS

How would you add a placeholder to an Editor in Xamarin Forms for iOS?
I tried adding through custom renderer as Control.Layer but could not find a property related to it.
Please help.
Try following code:
PCL:
using System;
using Xamarin.Forms;
namespace ABC.CustomViews
{
public class PlaceholderEditor : Editor
{
public static readonly BindableProperty PlaceholderProperty =
BindableProperty.Create<PlaceholderEditor, string>(view => view.Placeholder, String.Empty);
public PlaceholderEditor()
{
}
public string Placeholder
{
get
{
return (string)GetValue(PlaceholderProperty);
}
set
{
SetValue(PlaceholderProperty, value);
}
}
}
}
iOS (CustomeRenderer) :
using UIKit;
using ABC.CustomViews;
using ABC.iOS.CustomRenderer;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(PlaceholderEditor), typeof(PlaceholderEditorRenderer))]
namespace ABC.iOS.CustomRenderer
{
public class PlaceholderEditorRenderer : EditorRenderer
{
private string Placeholder { get; set; }
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
var element = this.Element as PlaceholderEditor;
if (Control != null && element != null)
{
Placeholder = element.Placeholder;
Control.TextColor = UIColor.LightGray;
Control.Text = Placeholder;
Control.ShouldBeginEditing += (UITextView textView) =>
{
if (textView.Text == Placeholder)
{
textView.Text = "";
textView.TextColor = UIColor.Black; // Text Color
}
return true;
};
Control.ShouldEndEditing += (UITextView textView) =>
{
if (textView.Text == "")
{
textView.Text = Placeholder;
textView.TextColor = UIColor.LightGray; // Placeholder Color
}
return true;
};
}
}
}
}
Usage :
_replyEditor = new PlaceholderEditor
{
Placeholder = "Placeholder Text"
};
below is the code for android
using System;
using MyApp;
using MyApp.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomEditor), typeof(CustomEditorRenderer))]
namespace MyApp.Droid
{
public class CustomEditorRenderer : EditorRenderer
{
public CustomEditorRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var element = e.NewElement as CustomEditor;
this.Control.Hint = element.Placeholder;
Control.Gravity = Android.Views.GravityFlags.Start;
Control.SetBackgroundColor(global::Android.Graphics.Color.White);
Control.SetPadding(15,15,15,15);
}
}
}
Here is a Xamarin forms version that allows a placehodler to be included in the initializer of the Editor, and also handles consistent behavior if the Text property is set in code (i.e. if Editor.Text="" it will show the placeholder in light gray.
using System;
using Xamarin.Forms;
namespace CrowdWisdom.Controls
{
public class EditorPlaceHolder : Editor
{
String placeHolderText = "";
public EditorPlaceHolder(String placeholder)
{
Text = placeholder;
TextColor = Color.LightGray;
this.Focused += EditorPlaceHolder_Focused;
this.Unfocused += EditorPlaceHolder_Unfocused;
this.placeHolderText = placeholder;
}
private void EditorPlaceHolder_Focused(object sender, FocusEventArgs e) //triggered when the user taps on the Editor to interact with it
{
if (Empty())
{
base.Text = "";
this.TextColor = Color.Black;
}
}
private void EditorPlaceHolder_Unfocused(object sender, FocusEventArgs e) //triggered when the user taps "Done" or outside of the Editor to finish the editing
{
if (Empty()) //if there is text there, leave it, if the user erased everything, put the placeholder Text back and set the TextColor to gray
{
this.Text = placeHolderText;
this.TextColor = Color.LightGray;
}
}
public String PlaceHolderText
{
get
{
return this.placeHolderText;
}
set
{
if (this.Empty())
{
this.Text = value;
this.TextColor = Color.LightGray;
}
this.placeHolderText = value;
}
}
public bool Empty()
{
return (this.Text.Equals("") || this.Text.Equals(this.placeHolderText));
}
public virtual new string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
if (Empty())
{
this.TextColor = Color.LightGray;
base.Text = this.placeHolderText;
}
else
{
this.TextColor = Color.Black;
}
}
}
}
}
Xamarin Forms adding a placeholder to an Editor for Android
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace MyCare.Renderers
{
class PlaceholderEditor : Editor
{
public static readonly BindableProperty PlaceholderProperty = BindableProperty.Create<PlaceholderEditor, string>(view => view.Placeholder, String.Empty);
public PlaceholderEditor()
{
}
public string Placeholder
{
get
{
return (string)GetValue(PlaceholderProperty);
}
set
{
SetValue(PlaceholderProperty, value);
}
}
}
}
//Renderer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using MyCare.Renderers;
using MyCare.Droid.Renderers;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(PlaceholderEditor), typeof(PlaceholderEditorRenderer))]
namespace MyCare.Droid.Renderers
{
class PlaceholderEditorRenderer : EditorRenderer
{
private string Placeholder { get; set; }
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
var element = this.Element as PlaceholderEditor;
if (Control != null && element != null)
{
Placeholder = element.Placeholder;
Control.SetTextColor(Android.Graphics.Color.Black);
Control.SetHintTextColor(Android.Graphics.Color.LightGray);
Control.Hint = element.Placeholder;
Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
}
}
}
}
Inherit from Jay's solution. Here is a usage in XAML
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:cstCtrl="clr-namespace:TeamCollaXform.Views"
x:Class="TeamCollaXform.Views.MailComposePage">
...
<cstCtrl:PlaceholderEditor Grid.Row="2" x:Name="txtContent" Text="" HeightRequest="750" Placeholder="Compose..."/>

Asynchronous http listener c#

I am developing a small SMS server in C# and want to make an asynchronous listener that processes requests sent to an SMS object (username, message, etc.). I want to create the asynchronous listener as a class library. Here is the code:
using System;
using System.Net;
using System.Threading;
namespace AListener
{
public class CAListener
{
public CAListener()
{
Thread listener = new Thread(new ParameterizedThreadStart(RequestListener));
listener.Start(new string[] { "http://*:11600/" });
}
private ManualResetEvent stopListener = new ManualResetEvent(false);
private object lockListener = new object();
private bool newRequest = false;
public void StopListener()
{
stopListener.Set();
}
public void RequestListener(object parameter)
{
string[] prefixes = parameter as string[];
HttpListener listener = new HttpListener();
foreach (string prefix in prefixes)
{
listener.Prefixes.Add(prefix);
}
listener.Start();
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
while (!stopListener.WaitOne(10))
{
lock (lockListener)
{
if (newRequest)
{
result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
newRequest = false;
}
}
result.AsyncWaitHandle.WaitOne(10);
}
listener.Close();
}
public void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
lock (lockListener)
{
newRequest = true;
}
}
}
}
I have a UI form where I obtain AListener object and everything here is OK.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AListener;
namespace ZNSMS
{
public partial class ZNSMSServer : Form
{
public ZNSMSServer()
{
InitializeComponent();
}
CAListener ca = null;
private void button1_Click(object sender, EventArgs e)
{
ca.StopListener();
}
private void ZNSMSServer_Load(object sender, EventArgs e)
{
ca = new CAListener();
}
}
}
But when I press the Button (I just want to stop the listener) - for some reason listener.Stop() kills my main UI Form ZNSMSServer. When I comment listener.Stop() it's working, but I think that's not the proper way and I cannot understand why calling listener.Stop() can impact (in this case Close?) the calling object - in this case ZNSMSServer.
If anyone has dealt with this kind of issue before, I would really appreciate it.
Thanks in advance.

Implement video streaming in java me using rtsp

I want to implement video streaming in java me using rtsp url. When tested the code on devices, I get Media Exception stating Prefetch Error-33. Here's my code
private void startStreaming()
{
try
{
mplayer=Manager.createPlayer(videourl);
mplayer.addPlayerListener(this);
mplayer.realize();
videoControl=(VideoControl) mplayer.getControl("VideoControl");
if(videoControl!=null)
{
Item video=(Item) videoControl.initDisplayMode(videoControl.USE_GUI_PRIMITIVE, null);
videoControl.setVisible(true);
System.out.println("Playing");
Form v=new Form("Playing Video");
StringItem si=new StringItem("Status", "Playing....");
v.append(video);
display.setCurrent(v);
}
mplayer.prefetch();
mplayer.start();
}
catch(Exception noCanDo)
{
Form f=new Form("Error");
f.append("Error : "+noCanDo);
display.setCurrent(f);
}
}
I have also tried using alternative method of using MIDlet.platformrequest(videourl) method which invokes default internal player of device to play video file. The player is being started but later on, a connection timeout prompt occurs. I have however tested the rtsp url and it works very much fine. Any suggestions as to how can I do video streaming using rtsp url in java me?
Use this code for streamin RTSP,it should work for nokia symbian belle sdk 1.1 and nokia sdk 2.0
protected void startApp() throws MIDletStateChangeException {
VideoCanvas VC = new VideoCanvas(this,url);
Display.getDisplay(this).setCurrent(VC); }
}
//videoCanvas Class
public VideoCanvas(ExampleStreamingMIDlet midlet, String url) {
this.midlet = midlet;
this.url = url;
addCommand(start);
addCommand(stop);
addCommand(back);
addCommand(exit);
setCommandListener(this);
this.setFullScreenMode(true);
}
public void commandAction(Command c, Displayable arg1) {
if(c == start) {
start();
}
public void start() {
try{
Player player = Manager.createPlayer(url);
player.addPlayerListener(this);
player.realize();
control = (VideoControl)player.getControl("VideoControl");
if (control != null) {
control.initDisplayMode(VideoControl.USE_DIRECT_VIDEO,this);
control.setDisplaySize(176,144);
int width = control.getSourceWidth();
int height = control.getSourceHeight();
status2 = "Before: SW=" + width + "-SH=" + height + "-DW=" + control.getDisplayWidth() + "-DH=" + control.getDisplayHeight();
}
player.start();
}
catch(Exception e) {
Alert erro = new Alert("Erro",e.getMessage(),null,AlertType.ERROR);
Display.getDisplay(midlet).setCurrent(erro);
}
}
public void stop() {
if(player != null) {
player.deallocate();
player.close();
}
}

Resources