I created the following code to play audio in my app. How can I stop the playback when the app is minimized? As of now, the audio will continue to play until the app is " destroyed "
backgroundMusicStream = Display.getInstance().getResourceAsStream(getClass(), "/backgroundMusic.mp3");
try {
backgroundMusic = MediaManager.createMedia(backgroundMusicStream, "audio/mp3", onComplete);
backgroundMusic.setVolume(35);
backgroundMusic.play();
} catch (Exception e) {
e.printStackTrace();
}
You can override the stop() method in the main class to stop "in progress" elements and invoke this code. You can debug this in the simulator using the Pause/Resume menu options.
BTW I would recommend using Log.e(exception) instead of printStackTrace().
Related
I'm using the ABP framework with WinForms and I need to identify the best way to intercept an exception and log this information.
My WinForms is a Multiple-Document Interface (MDI) application. I add a HandleException in Program.cs so that when the application throws an exception, I'm able to log it in the log file. But if I get an exception in an ApplicationService, this exception is handled by ABP and not thrown back to WinForms, and nothing is written in the log file.
Do I need to implement some interface to have the classic logging like MVC/Angular app?
UPDATE
I found that the problem is related to async operation. Usually I call:
await _service.GetProducts();
If an exception is thrown, the main thread does not intercept it. If I switch to:
AsyncHelper.RunSync(() => _service.GetProducts());
Then the main thread intercepts the error.
because the exception is thrown in another thread you have to handle unhandled exceptions of the application domain. insert the exception handler into the starting point of your application. for win forms i guess you can use program.cs
static class Program
{
[STAThread]
static void Main(string[] argv)
{
try
{
AppDomain.CurrentDomain.UnhandledException += (sender,e)
=> HandleException(e.ExceptionObject);
Application.ThreadException += (sender,e)
=> HandleException(e.Exception);
Application.Run(new MainWindow());
}
catch (Exception ex)
{
HandleException(ex);
}
}
static void HandleException(object exception) {
var ex= exception as Exception;
if (ex== null) {
ex= new NotSupportedException("Unhandled exception: " + exceptionObject.ToString());
}
//you can log exception here -> ex.ToString();
}
}
Ok after some invastigation and googling I found this MSDN explanation Asynchronous Programming - Async from the Start
Accoriding to this article I change my program start to move to async code.
I need to chage a little bit more because I'm on Mdi Form when open a inside form
Form1 childForm = Globals.Bootstrapper.IocManager.Resolve<Form1>();
childForm.MdiParent = this;
var formAsync = childForm.InitializeAsync();
FormExtension.HandleExceptions(formAsync);
childForm.Show();
I add the static class to intercept the error form Abp
public static async void HandleExceptions(Task task)
{
try
{
await Task.Yield(); //ensure this runs as a continuation
await task;
}
catch (Exception ex)
{
//deal with exception, either with message box
//or delegating to general exception handling logic you may have wired up
//e.g. to Application.ThreadException and AppDomain.UnhandledException
var log = Globals.Bootstrapper.IocManager.IocContainer.Resolve<ILogger>();
LogHelper.LogException(log, ex);
//Exception handling...
MessageBox.Show("Ops!" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Application.Exit();
}
}
Now my log file is populated in correct way
I have created an app for video demonstration using Codename one. I'm Facing some challenges when I'm running the app on my Google Android Phone as it does not allow a full screen view and also after the video is done playing, it does not go back or restart the video again. Another problem was that I had a button at the bottom at the borderlayout and each time I click the button, it corrupts the video and the video won't play anymore. These are codes used for my demonstration app Demonstration App 1, Demonstration App2 .
#Override
protected void postMain1(Form f) {
final MediaPlayer mp = findMpPresent();
try {
InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/sbuda.mp4");
if (is != null) {
mp.setDataSource(is, "video/mp4", null);
} else {
}
} catch (IOException ex) {
ex.getMessage();
}
}
This is a bit unclear since I can't see the stop/start etc with a GUI builder application.
You can use native on-device controls for playback using setFullScreen. Notice that this works nicely on the device but has no equivalent on the simulator.
Once playback is finished the media no longer exists as your input stream has been depleted. You will need to create a new Media object. You can use the completion callback (the Runnable argument) to detect the end of the media.
I am new to Sikuli. I am Automating a web application that have option to upload a file.
When I click on upload button it opens a popup window.In that window I have to select a file. How I can do it using sikuli.
I am using linux operating system so I can't use AutoIT.
Below is my code which I am trying
public static void imageClick()
{
Screen s= new Screen();
try {
s.capture();
s.find("Desktop.png");
s.click("Desktop.png",0);
System.out.println("Desktop is selected");
} catch (FindFailed e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Desktop.png is a image file which I kept in my project. first I am searching it then clicking on it.
Anyone can help me how I can achieve this. Any help will be highly appreciated.
Finally I done in in below way
First import sikuli jar file to your project
Capture the Image where you want to click and save it to some location
for Ex. /home/dev/Desktop/abc.png
Screen s = new Screen(); //Created the Object of screen class
s.click("/home/dev/Desktop/abc.png");
public static void imageClick()
{
Screen s= new Screen();
Pattern DesktpIcon = new Pattern("Desktop.png");
s.click(DesktpIcon);
System.out.println("Desktop is Clicked.");
}
I am developing an application using codenameone that needs to download an audio file (mp3)
from a remote server, and then play it once the download is complete.
I want it to happen once a button is clicked, but so far...all i see in the simulator is the infinite dialog and nothing else.
I am using java 7 on my development pc.
Here are relevant code snippets:
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String file=_cat+".mp3";
String path="/"+file;
Util.downloadUrlToStorage("http://abcde.com/images/"+file,path,true);
final InputStream is = Display.getInstance().getResourceAsStream(this.getClass(), path);
try {
Media mm = MediaManager.createMedia(is, "audio/mp3");
mm.play();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
How can i get to download the audio file and play it once it completes?.
I edited my code in line with shai almog's answer, to the following:
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String file=_cat+".mp3";
Util.downloadUrlToStorage("http://abcde.com/images/"+file,file,true);
try {
is = Storage.getInstance().createInputStream(file);
} catch (IOException ex) {
ex.printStackTrace();
}
try {
Media mm = MediaManager.createMedia(is, "audio/mp3");
mm.play();
}
catch (IOException ex) {
ex.printStackTrace();
}
....and still nothing gets downloaded....i go to the
.CodenameOneStorage
directory on my PC but nothing there..i guess
i am missing something
getResourceAsStream returns a stream into a jar and is a read only path. Its not a "file" and you can't write there. Storage is a simplified file system that is unrelated to that either.
You can use something like:
Util.downloadUrlToStorage("http://abcde.com/images/"+file,file,true);
InputStream is = Storage.getInstance().createInputStream(file);
I have a WPF Caliburn.Micro application, and I use MediaPlayer class to play audio. I implemented Play, Stop, and Pause functionality, but I don't see a method for Resume (after Pause) in MediaPlayer. Could you please help me with this?
Here is some of my code:
public void Play()
{
try
{
var audio = Tpv.GetAudio(SelectedTpv.TpvId);
var file = Path.GetTempFileName().Replace(".tmp", ".wma");
File.WriteAllBytes(file, audio);
Player.Open(new Uri(file, UriKind.Absolute));
Player.Play();
IsPlaying = true;
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Failed to play audio:\n{0}", ex.Message), "Failure",
MessageBoxButton.OK, MessageBoxImage.Error);
Console.WriteLine(ex.Message);
}
}
Thanks.
I'm pretty sure that Play is also supposed to handle resume functionality. According to the MSDN for System.Windows.Media.MediaPlayer the Play method is supposed to "Play media from the current Position". This means that when you are playing media from the beginning, the position is 0. If you pause, then the media will be paused at a certain position. Pressing play again should resume playback from the same position that you paused the media on.
Edit:
Based on the code update you provided, it looks like your issue is that you are loading the file each time you click play. This would cause any previous pause information to be erased, and would treat the file as being brand new each time. You should put some sort of check in there to say that if the file is not already loaded, then load it. Otherwise, your Play method should just call Player.Play() to resume.
I would also note that you would need to also call Player.Close when you switch the selected item. This would let the Play method know that it needs to load a different file.
public void Play()
{
try
{
// Check if the player already has a file loaded, otherwise load it.
if(Player.Source == null) {
var audio = Tpv.GetAudio(SelectedTpv.TpvId);
var file = Path.GetTempFileName().Replace(".tmp", ".wma");
File.WriteAllBytes(file, audio);
Player.Open(new Uri(file, UriKind.Absolute));
}
Player.Play();
IsPlaying = true;
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Failed to play audio:\n{0}", ex.Message), "Failure",
MessageBoxButton.OK, MessageBoxImage.Error);
Console.WriteLine(ex.Message);
}
}