Here is the code I am having problem with.
if (ADi == 1) {
if (RS >= 10)
System.out.println("oooooooo");
{ // TODO codes incomplete
System.out.println("ohhhhh");
vib2.vibrate(600);
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.beep02);
mp.start();
}
finish();
}
The problem is it don’t check RS>=10 its simply play the mp and vibrate . RS = 0 . I am not getting this out put "ooooooo" I am getting "ohhhhh" . I don’t want to play mp and vibrate if RS < 10 .
Any help is much appreciated .
If i m not wrong you are committing a very silly mistake...
if (ADi == 1)
{
System.out.println("oooooooo");
if (RS >= 10)
{
System.out.println("ohhhhh");
vib2.vibrate(600);
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.beep02);
mp.start();
}
else
finish();
}
If you compare your code the only thing i did was to move System.out.println("oooooooo");
above if(RS>=10) since you said System.out.println("oooooooo"); is printing it means your RS is working but you are consuming it by printing that "ooooo" . System.out.println () is also a statement and line of code .And since your RS is consumed hence the code including Mediaplayer are called independantly of RS condition.
Btw i think you should be calling finish in else
Hope it helps... thx
You are missing the "else"! It helps if you format your code in a more readable way:
if (ADi == 1)
{
if (RS < 10)
{
System.out.println("oooooooo");
}
else
{ // TODO codes incomplete
System.out.println("ohhhhh");
vib2.vibrate(600);
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.beep02);
mp.start();
}
finish();
}
Try this one :
if (ADi == 1)
{
if (RS >= 10)
{
System.out.println("ohhhhh");
vib2.vibrate(600);
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.beep02);
mp.start();
}
else {
System.out.println("oooooooo");
}
finish();
}
Related
So this is the simple code I use to play an audio file in my app:
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
And here is the error log:
java.io.IOException: Prepare failed
at android.media.MediaPlayer._prepare(Native Method)
This error makes the app freeze for like 10 seconds and happens when the url providing the mp3 file returns 404 (not found). So how can I solve the issue?
I have used mediaPlayer.prepareAsync(), but nothing changed.
Please try the below way, the below code is in kotlin but you can use this way in java
mPlayer = MediaPlayer.create(mContext, myUri(uriAudio))
if (Build.VERSION.SDK_INT >= 21) {
val audioAttributes: AudioAttributes =
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
mPlayer!!.setAudioAttributes(audioAttributes)
} else {
mPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
}
if (mPlayer != null && !mPlayer!!.isPlaying) {
mPlayer!!.start()
}
You can try below method:
https://developer.android.com/reference/android/media/MediaPlayer#setAudioStreamType(int)
the method, setAudioStreamType, was deprecated in API level 26.
use setAudioAttributes(android.media.AudioAttributes)
I'm currently using FFmpegMediaPlayer from github and the effects are not working in the phone but works perfectly in the emulator which of both are the same API 22.
The strange thing is that when I switch the code from FFmpegMediaplayer to standard android media player the effects start working again in the real phone device. But when I switch back to ffpmeg the effect only works in the emulator and not in the real device. My code is as below,
public void setupVisualizerFxAndUI() {
try {
mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
mEqualizer = new Equalizer(0, mMediaPlayer.getAudioSessionId());
mEqualizer.setEnabled(true);
try {
bassBoost = new BassBoost(0, mMediaPlayer.getAudioSessionId());
bassBoost.setEnabled(false);
BassBoost.Settings bassBoostSettingTemp = bassBoost.getProperties();
BassBoost.Settings bassBoostSetting = new BassBoost.Settings(bassBoostSettingTemp.toString());
bassBoostSetting.strength = (1000 / 19);
bassBoost.setProperties(bassBoostSetting);
mMediaPlayer.setAuxEffectSendLevel(1.0f);
presetReverb = new PresetReverb(0, mMediaPlayer.getAudioSessionId());
presetReverb.setPreset(PresetReverb.PRESET_NONE);
presetReverb.setEnabled(false);
mMediaPlayer.setAuxEffectSendLevel(1.0f);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
if (homeActivity.isEqualizerEnabled) {
try {
bassBoost.setEnabled(true);
BassBoost.Settings bassBoostSettingTemp = bassBoost.getProperties();
BassBoost.Settings bassBoostSetting = new BassBoost.Settings(bassBoostSettingTemp.toString());
if (homeActivity.bassStrength == -1) {
bassBoostSetting.strength = (1000 / 19);
} else {
bassBoostSetting.strength = homeActivity.bassStrength;
}
bassBoost.setProperties(bassBoostSetting);
mMediaPlayer.setAuxEffectSendLevel(1.0f);
if (homeActivity.reverbPreset == -1) {
presetReverb.setPreset(PresetReverb.PRESET_NONE);
} else {
presetReverb.setPreset(homeActivity.reverbPreset);
}
presetReverb.setEnabled(true);
mMediaPlayer.setAuxEffectSendLevel(1.0f);
} catch (Exception e) {
e.printStackTrace();
}
}
if (homeActivity.isEqualizerEnabled && homeActivity.isEqualizerReloaded) {
try {
homeActivity.isEqualizerEnabled = true;
int pos = homeActivity.presetPos;
if (pos != 0) {
mEqualizer.usePreset((short) (pos - 1));
} else {
for (short i = 0; i < 5; i++) {
mEqualizer.setBandLevel(i, (short) homeActivity.seekbarpos[i]);
}
}
if (homeActivity.bassStrength != -1 && homeActivity.reverbPreset != -1) {
bassBoost.setEnabled(true);
bassBoost.setStrength(homeActivity.bassStrength);
presetReverb.setEnabled(true);
presetReverb.setPreset(homeActivity.reverbPreset);
}
mMediaPlayer.setAuxEffectSendLevel(1.0f);
} catch (Exception e) {
e.printStackTrace();
}
}
where mMediaPlayer is ffmpeg...Other than that the library is working fine in regards to streaming. The only problem is that it doesn't get any effect put in. I thought this might be a coding problem so I just switched ffmpeg with Android standard media player like I mentioned above and it works. FFmpeg - bass boost and equalizer only works in the emulator and not in real phone device.
Another strange thing was that the effect initially worked at first in debug run mode and stopped working after I signed the apk. From which point on it stopped working both in the debug as well as any other run modes i.e - release also....I'm not using any pro guard rules also.
Points to note :
1. Replacing FFmpegmediaplayer with Standard Media player the effects works.
2. Effects worked before signing the apk then stopped working in all run modes
3. Using the same code above for FFMpegmediaplayer effects only work in the
Emulator and not in real device.
4. Other than the effects problem, FFmpegmediaplayer is functional regarding
streaming and local playback - in real phone device as well as emulator.
Never mind found the answer myself. For those of you having the same problem I suggest changing the libraries manually and hope it works. Cause its an issue or a bug related to the library being used.
I want to make an entertainment app which will produce sound only when the play button is pressed, but it is not working properly .
My code is
final MediaPlayer mp = new MediaPlayer();
play.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try{
AssetFileDescriptor descriptor = getAssets().openFd("3dpolicesi_mAYkXAbm.mp3");
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
mp.setDataSource(descriptor.getFileDescriptor(), start, end);
mp.prepare();
mp.start();
mp.stop();
}catch(Exception e){e.printStackTrace();}
}
} );
It is because mp.stop() is called directly after mp.start(). It won't get a chance to play.
First delete this 3 line of your code:
mp.prepare();
mp.start();
mp.stop();
Write this outside of onClick:
int x = 0;
Then write this inside of onClick:
if(x == 0){
mp.start();
x = 1;
}else if(x == 1){
mp.stop();
x = 0;
}
At first time x is 0 so when you click on button player will be start and x will be replace with 1. next time when you click on button x is 1 so player will be stop.I hope it help.
My objective is to create a VideoView that can play videos in a pre-defined play list.
I'm trying to use MediaPlayer.setNextMediaPlayer(...) to allow a seamless transition between two videos. However, when the first video finishes playing, the 2nd video will not start automatically as it should according to the documentation.
Xamarin Android Code:
Queue<MediaPlayer> MediaPlayerList = null;
private void PlayVideo()
{
MediaPlayerList = new Queue<MediaPlayer>();
//Let's go ahead and create all media players
VideoView_CurrentVideoView = new VideoView(this);
VideoView_CurrentVideoView.Completion += mVideoView_Completion;
VideoView_CurrentVideoView.Prepared += mVideoView_Prepared;
//Let's prepare all MediaPlayer
for (int i = 0; i < VideoView_CurrentVideoChannel.VideoAssetList.Count; i++)
{
string filePath = FilePath[i];
if (i == 0)
{
VideoView_CurrentVideoView.SetVideoPath(filePath);
VideoContainer.AddView(VideoView_CurrentVideoView);
}
else
{
MediaPlayer mpNew = new MediaPlayer();
mpNew.SetDataSource(filePath);
MediaPlayerList.Enqueue(mpNew);
}
}
VideoView_CurrentVideoView.Start();
}
void mVideoView_Completion(object sender, EventArgs e)
{
MediaPlayer mp = (MediaPlayer)sender;
mp.Release();
}
void mVideoView_Prepared(object sender, EventArgs e)
{
MediaPlayer mp = (MediaPlayer)sender;
//Take the next available MediaPlayer from the queue
MediaPlayer nextMediaPlayer = MediaPlayerList.Dequeue();
//Put the current MediaPlayer at the end of the queue
MediaPlayerList.Enqueue(mp);
nextMediaPlayer.Prepare();
mp.SetNextMediaPlayer(nextMediaPlayer);
}
Any help or suggestions will be greatly appreciated. This is coded in Xamarin Android.
Update #1: After moving the .Prepare() away from Prepared() event
Queue<string> VideoListQueue = null;
MediaPlayer NextMediaPlayer = null;
private void PlayVideo()
{
string filePath = FilePath[0];
//Create video view
if (VideoContainer.ChildCount == 0)
{
//setup the videoview container
VideoView_CurrentVideoView = new VideoView(this);
VideoView_CurrentVideoView.Info += VideoView_CurrentVideoView_Info;
VideoView_CurrentVideoView.Error += VideoView_CurrentVideoView_Error;
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent);
param.LeftMargin = 0;
param.RightMargin = 0;
param.BottomMargin = 0;
param.TopMargin = 0;
VideoView_CurrentVideoView.LayoutParameters = param;
VideoView_CurrentVideoView.LayoutParameters.Width = ViewGroup.LayoutParams.FillParent;
VideoView_CurrentVideoView.LayoutParameters.Height = ViewGroup.LayoutParams.FillParent;
VideoView_CurrentVideoView.Completion += VideoView_CurrentVideoView_Completion;
VideoView_CurrentVideoView.Prepared += VideoView_CurrentVideoView_Prepared;
VideoContainer.AddView(VideoView_CurrentVideoView);
}
VideoView_CurrentVideoView.SetVideoPath(filePath);
VideoView_CurrentVideoView.SeekTo(0);
VideoView_CurrentVideoView.Start();
}
void VideoView_CurrentVideoView_Prepared(object sender, EventArgs e)
{
//Do nothing at this moment
MediaPlayer mp = (MediaPlayer)sender;
}
void VideoView_CurrentVideoView_Completion(object sender, EventArgs e)
{
//GC the finished MediaPlayer
MediaPlayer mp = (MediaPlayer)sender;
mp.Reset();
mp.Release();
mp = null;
//Preparing the next MediaPlayer
MediaPlayer currentPlayer = NextMediaPlayer;
NextMediaPlayer = SetupNextMediaPlayer();
currentPlayer.SetNextMediaPlayer(NextMediaPlayer);
}
MediaPlayer SetupNextMediaPlayer()
{
MediaPlayer mp = new MediaPlayer();
//When the video start playing, let's get ready for next one
string sourceURL = VideoListQueue.Dequeue();
VideoListQueue.Enqueue(sourceURL);
string filePath = sourceURL;
mp = new MediaPlayer();
mp.Info += VideoView_CurrentVideoView_Info;
mp.Completion += VideoView_CurrentVideoView_Completion;
mp.Prepared += VideoView_CurrentVideoView_Prepared;
mp.SetDataSource(filePath);
mp.Prepare();
//Fire back the created MediaPlayer object to the caller
return mp;
}
void VideoView_CurrentVideoView_Info(object sender, MediaPlayer.InfoEventArgs e)
{
Console.WriteLine("What = " + e.What);
switch (e.What)
{
case MediaInfo.VideoRenderingStart:
{
//This is only happening on video first started
NextMediaPlayer = SetupNextMediaPlayer();
e.Mp.SetNextMediaPlayer(NextMediaPlayer);
break;
}
}
}
void VideoView_CurrentVideoView_Error(object sender, MediaPlayer.ErrorEventArgs e)
{
e.Handled = true;
}
At this moment, the media player will begin playing the 2nd video once the first one is done. However, the 2nd video only have sound and no video showing.
Anyone know what I did wrong? I have a feeling that it has to do something with the MediaPlayer not attached to the SurfaceView. However, I created the view using VideoView, how can I get the Surface from VideoView?
Regarding playing 2nd video only with sound: try to implement OnCompletionListener listener for each MediaPlayer with this:
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.setDisplay(null); //for current mediaPlayer
nextMediaPlayer.setDisplay(getHolder()); //for next video
}
});
I can't say that is is gapless, but somehow it works. To archive this I don't use standard VideoView, but custom View, that extends from SurfaceView.
what if you prepare and play the next mediaplayer on .Completion event? have you try it? although it may have a small delay
After many years of testing, this problem does not happen on all hardware. For example, I run the same APK on Nexus7, it appears to be seamless and everything is working. In contrast, if I run it on Amlogic media player board, it will render the above-described problem.
I decided to close this post off with a conclusion that it is something to do with the hardware. I know someone overcome this limitation by run everything in OpenGL, but that is completely a separate beast to deal with.
Conclusion
If you are having a similar problem as described above, there's nothing much you can do as it is heavily dependent on the hardware.
I use MediaPlayer for playing a single MP3 song from network. Data source is the file downloaded from network. This files comes in chuncks.
Let's assume we have following playing state.
Song duration: 4:00
Current chunck loaded in player: 1:00
Let's say I want to skip some part of a song and seek forward. I do it with MediaPlayer.seekTo() method. If I seek to position (1:40) it is not performed correctly, seek bar goes at start position (00:00) and the playerr stops.
public static void seekTo(int progress) {
try {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(sFilePath);
mp.prepare();
int offset = (progress * mp.getDuration()) / 100;
if (sCompleted)
return;
sLastSeek = offset;
if (offset > sMediaPlayer.getDuration()) {
sMediaPlayer.reset();
sMediaPlayer.setDataSource(sFilePath);
sMediaPlayer.prepareAsync();
} else {
sMediaPlayer.seekTo(offset);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}