JavaFX MediaPlayer loop - java

I am working on a simpel game and I would like to have a video background. I first did this using a gif but this runs kind of slow. Now I created a video background using the mediaplayer and it works perfectly.
The video show without a problem.
The only problem I have is that the video does not want to loop. I tried every single aproache i found on the internet but nothing seems to work.
The video always plays 1 time and then stops.
I am using the java JDK8. Windows 10, 64 bit.
This is my code:
Media media = new
Media(getClass().getClassLoader().getResource("img/menu.mp4").toString());
MediaPlayer player = new MediaPlayer(media);
player.setAutoPlay(true);
player.setCycleCount(MediaPlayer.INDEFINITE);
MediaView view = new MediaView(player);
All of this is inside a stackpane.
I have tried exporting the mp4 to flv but this does not work.
If anyone knows different ways to create a video background, everything is welcome.
Edit:
So far no luck, I was thinking of using:
player.setOnEndOfMedia(new Runnable() {
#Override
public void run() {
player.seek(Duration.ZERO);
}
});
But not even this works..

Probably it's a bit late but you forgot to play after seeking to duration zero.
player.setOnEndOfMedia(new Runnable() {
#Override
public void run() {
player.seek(Duration.ZERO);
player.play();
}
});
It worked for me

From the MediaPlayer API:
Media playback commences at startTime and continues to stopTime. The interval defined by these two endpoints is termed a cycle with duration being the difference of the stop and start times. This cycle may be set to repeat a specific or indefinite number of times.
So you need to set startTime and stopTime before cycling works. For example (for a 5 second video):
player.setStartTime(Duration.seconds(0));
player.setStopTime(Duration.seconds(5));

Related

Android studio - mediaPlayer

I'm doing a project on Android Studio and I've got a problem:
I have changed the volume of the media in one activity and I've tried to move the media to the second activity.
I've succeded to move the audio to the second activity but it was without any volume change...
How can I fix it?
update:
Hi, because I can't save the changes that I have made in my mediaPlayer I decided to record the song before I moving between the activitys.
I got a problem with the mediaRecorder - I can't start recording and I have no idea what is wrong in my code...
my code:
rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(secondRemix.this, "You are starting the recording, you need to wait a little bit until it will be ready.",
Toast.LENGTH_SHORT).show();
FILE = Environment.getExternalStorageState()+"/tempRecord.3gpp";
record.setAudioSource(MediaRecorder.AudioSource.MIC);
record.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
record.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
record.setOutputFile(FILE);
record.start();//check it!!!
song.start();
startActivity(new Intent(secondRemix.this,waitScreen.class));
record.stop();
record.release();
can anybody help me with that? –
Thank you!
Is not a properly answer but might help. Short: you can't.
Why?
The native Media Player uses canvas to render the frames and it is automatic cleaned when is not on the screen.
Workaround 1: When you start the video on the new Activity automatically start from the position that the user stopped.
Workaround 2 (Like Youtube): Use fragments to manage your view.

How to keep monitoring the time without a while loop in Android

I am developing an app that will play certain sound at 9:15AM and 10:30AM in the morning,
I am done with playing the sound part already but I am facing issues while monitoring the current android system time.
Here is what I am doing,
I have an array where 9:15AM and 10:30AM are stored as String.
While I am using Java Calendar class to get current time of the System,
Calendar cTime = Calendar.getInstance();
public String currentTime() {
String hour = cTime.get(Calendar.HOUR) + "";
String mins = cTime.get(Calendar.MINUTE) + "";
return hour+""+mins+"AM";
}
and I am playing the sound using this code,
public void playSound() {
MediaPlayer player = MediaPlayer.create(this, R.raw.s);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
The problem is,
If it is 9:15AM in the morning and I run the app then the app would play the sound, or if it is 10:30 in the morning and I run the app then App will play the sound, but this isn't what I want,
I want my app to keep monitoring the time all the time and when its 9:15AM or 10:30AM, the sound should play regardless of the app is running or not.
i tried one approach by comparing the current time with 10:30AM or 9:30AM in a while loop, but it hangs my phone and this seems ugly idea.
I couldn't think of any other way to monitor the time, please suggest me something.
Use AlarmManager to schedule to get control at those points in time.
I think you should try these codes ( Android apis)
Use AlarmManager class to schedule and execute actions/operations that you want to perform regardless of the status of your android application whether it's running or not.
But before applying this concept you you should go through more details about this class , as it provides two types of alarm Elapsed Realtime and Real Time Clock..
and you will have to use BroadcastReceiver to receive the Intent .
if you want to use loops the you should use following codes(better than java calendar classes)
Time t = new Time();
t.setToNow();
or more better codes will be because now you will get current time zone of your user , so here you go;
Time t = new Time(Time.getCurrentTimezone());
t .setToNow();

Play audio stream with JavaFX

I'm trying to make simple audio player with JavaFX Mediaplayer component. All local files are fine but i want also implement internet radio.
Code:
public static void main(String[] args) throws URISyntaxException {
new JFXPanel(); //init jfx library
String u = "http://91.121.164.186:8050";
Media m=null;
try {
m = new Media(u);
} catch (MalformedURLException e) {
e.printStackTrace();
}
MediaPlayer player = new MediaPlayer(m);
System.out.println("play");
player.play();
player.setVolume(new Double(1));
}
When I run it like this there is no errors but there is no audio. What's wrong ? What are other posibilities to play radio stream in Java ?
In your current example I can see two errors,
You are trying to run a JAVAFX component on a non-Javafx thread, which will result in error. Try running your program inside the start method. Please go through How to use JavaFX MediaPlayer correctly?
The URL you are trying to access must be a Media Compoenent
Try going through this extremely great example on Javafx Media
http://docs.oracle.com/javafx/2/media/EmbeddedMediaPlayer.zip
N.B. The example has lot more data than your require, but its a great example !
"http://91.121.164.186:8050" is a website, (HTML document), not a audio file. You need to download an audio file, something that the player knows what to do with.

MediaPlayer seekTo() doesn't update SurfaceView

I already saw a lot of questions regarding issues about Android's MediaPlayer, most of them because of the seekTo() function. Now I tried to use it, and it worked just as expected: badly!
This function seems to be very inconsistent, specially when we want to provide its functionality while the video is paused. In my case, I have videos of 30 to 60 frames and I want to play them one by one - without that delay that MediaMetadataRetriever.getFrameAtTime() provides.
The problem I'm facing is when I call seekTo(), it doesn't update the SurfaceView. It only works in the first time, after that the SurfaceView just stays the same, it never gets updated again.
I heard a rumor that seekTo() only works with a minimum interval of 1 second, but I tested with a longer video and seeking second by second didn't work either.
Code
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mSurfaceHolder.addCallback(this);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setOnSeekCompleteListener(new OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer mp) {
// Need this postDelayed(), otherwise the media player always
// returns 0 in getCurrentPosition(), don't know why...
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mMediaPlayer.pause();
}
}, 100);
}
});
mMediaPlayer.setDataSource(localfile_source);
mMediaPlayer.prepare();
// Set the initial position.
mMediaPlayer.start();
mMediaPlayer.seekTo(500);
/**
We're assuming that targetMs is within 0 and the video's duration.
Also, targetMs is calculated to always move to the next/previous frame:
Example: currentMs + ( 1000 / framerate)
(if framerate = 20, then it will exist a frame in each 50ms)
*/
private void seekTo(int targetMs) {
mMediaPlayer.start();
mMediaPlayer.seekTo(targetMs);
}
Note that because of a known bug regarding using this function while the video is paused, is used a workaround:
Start the video;
Call seekTo();
Pause it on onSeekComplete().
From [this question]:
"You cannot do frame by frame seeking by using the MediaPlayer API's
provided by Android.
If you really want implement frame by frame seeking then you will have
to use a 3rd party multimedia framework like FFMPEG or you will need
to implement your own."
I created some test code to try it out anyway. I did not start() the video before using seekTo()—I just used seekTo() while paused.
When I moved forward in 50ms increments, I saw a series of about 4-5 frames repeat until roughly 2 seconds had elapsed; then, the set of preview frames changed to a new series of 4-5 frames. This seems to align with my previous trial wherein I moved forward in increments of 2000ms and saw a unique frame for each seekTo() call.
In summary, it appears that MediaPlayer picks several frames in each 2-second interval to be used as preview frames when the video is paused.

play video using jmf repeat automcatically

hello friends
i dont know more about jmf i play video using java media framework. now
How Can repeat video automatically means video play for ever until usr press stop button
thanks
"Reaching the end of play (signaled by an EndOfMedia event) is dealt with by setting the media's own time to zero (back to the start) and restarting the Player" [Book: (Java™ Media APIs: Cross-Platform Imaging, Media, and Visualization)]
In the code below, the object p is a player.
p.addControllerListener(new ControllerListener() {
public void controllerUpdate(ControllerEvent event) {
if (event instanceof EndOfMediaEvent) {
p.setMediaTime(new Time(0));
System.out.println("End of Media – restarting");
p.start();
}
}
});
After creating the player, you could add a ControllerListener. When the file ends an EndOfMediaEvent is generated. When you get that event, you can use the function setMediaTime(0) to start playing the file from the beginning
With an mp3, I had to call both player.start() and player.setMediaTime(new Time(0.)). Otherwise it would not replay any other way.

Categories