I have a splahs screen in my application and i am playing a video on that activity. But in some Android versions ( i mean old ) the video doesnt play. i dont know what to do..
here is some of my code
public void PlayVideo(){
try{
videoPlayer.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.afad_splash_ip4));
videoPlayer.prepare();
}
catch (Exception e){
}
try {
AssetFileDescriptor descriptor = getAssets().openFd("splash.mp4");
videoPlayer.reset();
videoPlayer.setDataSource(descriptor.getFileDescriptor());
videoPlayer.prepare();
}
catch (Exception ex)
{
try
{
Log.v("video ", "catch");
videoPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
videoPlayer.setVolume(0f, 0f);
videoPlayer.start();
videoPlayer.setLooping(false);
videoPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Intent i = new Intent(VideoSplash.this,ListActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
overridePendingTransition(R.anim.slide_in_top,R.anim.slide_out_bottom);
finish();
}
});
}
catch (Exception e)
{ //TODO
//Burada Video yerine resim koymalısın
//Kimi cihazlarda video oynamayabilir
Log.v("resim", "catch");
//Thats where i want to put a pic as a backgroun to my SurfaceView. and make it wait 10 secs
// videoSurface.setBackgroundDrawable(getResources().getDrawable(R.drawable.son_frame));
}
//TODO
//Burada Video yerine resim koymalısın
//Kimi cihazlarda video oynamayabilir
}
}
Try this code will help you
public class VideoPlayerActivity extends Activity implements OnErrorListener,
OnPreparedListener {
LoadAsyncTask video_async_task;
private VideoView mVideoView
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.video);
mVideoView = (VideoView) findViewById(R.id.mysurfaceview);
mVideoView.setMediaController(myctrl);
mVideoView.requestFocus();
video_async_task = new LoadAsyncTask();
video_async_task.execute();
}
private class LoadAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
mVideoView.setVideoURI(Uri.parse(path));
}
}
Related
Opening app without any error. But can't play music. But can play music from local machine. Internet connection is fine.
I have enabled internet permission in AndroidManiFest.xml
<uses-permission android:name="android.permission.INTERNET" />
I have enabled http permission.
android:usesCleartextTraffic="true"
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mP) {
Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
mP.start();
}
});
mediaPlayer.prepareAsync();
Full Code:
https://paste.ubuntu.com/p/dsjbg7YMNn/
I have tested your code and sometimes it works, sometimes it doesn't. If you search on Stack Overflow you will find plenty of similar problems.
You have 2 options:
Migrate to ExoPlayer2 which is far superior that MediaPlayer.
It doesn't work to play the sound in OnPreparedListener, but you can play it on button click, after it's prepared:
public class MainActivity extends AppCompatActivity {
private Button streamButton;
private boolean isPrepared = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(mp -> {
Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
isPrepared = true;
streamButton.setVisibility(View.VISIBLE);
});
mediaPlayer.setOnCompletionListener(mp -> {
mp.release();
isPrepared = false;
streamButton.setVisibility(View.INVISIBLE);
});
mediaPlayer.prepareAsync();
streamButton = findViewById(R.id.streamButton);
streamButton.setOnClickListener(v -> {
if (isPrepared) {
mediaPlayer.start();
}
});
}
}
try this:
if(mediaPlayer != null ){
if (mediaPlayer.isPlaying()){mediaPlayer.stop();}
mediaPlayer.reset(); //this line is important!
String path = File.separator + "sdcard" + File.separator + utilsFields.repoDirRoot + File.separator + media.mp4;
try {
mediaPlayer.setDataSource(path);
}catch (Exception ignored){}
try {
mediaPlayer.prepare();
}catch (Exception ignored){}
mediaPlayer.start();
}
I am having 3 tones. I am calling playmusic() function to play 2 of these tones on imageview toggle. when i click on imageview for first time tone1 starts playing. when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
my requiremet is , when i click on imageview for -
(1st time - tone1 should start playing).
(2nd time - tone1 should stop playing and tone2 should start playing)
(3rd time - tone2 should stop playing and tone1 should start playing again)
and so on....
String file=null;
int x=0;
public void playMusic(int i) {
x=i;
if(i==1){
file = R.raw.tone1;
}else if(i==2){
file = R.raw.tone2;
}else{
file = R.raw.tone3;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
Main2Activity.this.getResources().openRawResourceFd(file);
if(assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
I did a small modification on your logic and added mediaplayer.reset(). Here is the solution link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView player = findViewById(R.id.play);
player.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
playMusic(1);
}
});
mediaPlayer = new MediaPlayer();
}
int file = 0;
MediaPlayer mediaPlayer;
int x = 0;
public void playMusic(int i) {
x = x + i;
if (x == 1) {
file = R.raw.tone1;
}
else if (x == 2) {
file = R.raw.tone2;
} else {
x = 0;
file = R.raw.tone3;
}
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
MainActivity.this.getResources().openRawResourceFd(file);
if (assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
}
when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
If that's the only issue, try putting the following line before you call mediaPlayer = new MediaPlayer();:
if (mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
I'm building an application to live stream video from the raspberry pi to my android device. I have three functional ways of playing this stream:
rtsp://media.smart-streaming.com/mytest/mp4:sample_phone_150k.mp4
Media Player + SurfaceView
VideoView
Intent.ACTION_VIEW
The problem is the application plays the above^ stream but doesn't play mine (rtsp://192.168.1.143:8554/vid.mp4) ... but VLC does.
I have tried streaming with VLC and with LIVE555 in multiple video formats and I've also tried playing a video that was recorded on the phone.
Here is my code:
//Stream methods 0 = MediaPlayer & SurfaceView, 1 = VideoView, 2 = Native Video Player
final int STREAM_USING = 0;
//MediaPlayer on surfaceView
String streamPath = "rtsp://192.168.1.143:8554/vid.mp4";//"rtsp://media.smart-streaming.com/mytest/mp4:sample_phone_150k.mp4";//"rtsp://192.168.1.143:8554/vid.mp4";//;"rtp://239.255.0.1:5004/";
Uri streamUri;
private MediaPlayer mediaPlayer;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
//VideoView
VideoView videoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//MediaPlayer
switch (STREAM_USING) {
case 0: {
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setFixedSize(800, 480);
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
//mediaPlayer.stop();
play();
}
return false;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Toast.makeText(getApplicationContext(), "BUFF : " + percent, Toast.LENGTH_SHORT).show();
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
});
//Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//i.setType("video/*");
//startActivityForResult(i, 1234);
streamUri = Uri.parse(streamPath);
play();
break;
}
case 1: {
videoView = (VideoView) findViewById(R.id.videoView);
videoView.setVideoURI(Uri.parse(streamPath));
MediaController mediaController = new MediaController(this);
//mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.requestFocus();
try {
videoView.start();
}
catch (SecurityException se) {
Log.e("SE", se.getMessage());
se.printStackTrace();
}
break;
}
case 2: {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(streamPath));
startActivity(intent);
break;
}
default: {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(streamPath));
startActivity(intent);
}
}
}
private void play() {
try {
//final FileInputStream fis = new FileInputStream(streamPath);
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(MainActivity.this, streamUri);
//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
//mediaPlayer.reset();
mediaPlayer.start();
}
});
} catch (SecurityException se) {
Log.e("SE", se.getMessage());
se.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
Any help is appreciated, I've been trying for a week to get this to work with no success :(
You already added two ways just i want to add bit modification. I have done streaming ralalted task.I have used rtsp with wowza.Few ways i'll let you know
try it once and let me know if you got issue.If your streaming in vlc working fine then something problem with app side. If these methods are not working then try with different phone. It also help you.
1. Try with videoview
vvVideoPlay = (VideoView) findViewById(R.id.vvVideoPlay);
MediaController mediaController = new MediaController(this);
String videoUrl = "rtsp://192.168.1.143:8554/vid.mp4";
mediaController.setAnchorView(vvVideoPlay);
Uri uri = Uri.parse(videoUrl);
vvVideoPlay.setVideoURI(uri);
vvVideoPlay.setMediaController(mediaController);
vvVideoPlay.requestFocus();
vvVideoPlay.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
pdialog.dismiss();
mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mp.start();
}
});
}
});
2. Try with direct your phone player
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("rtsp://192.168.1.143:8554/vid.mp4")));
3. Third way try to with this library with custom player in your app.
Step1. Add it to your gradle
compile "fm.jiecao:jiecaovideoplayer:4.7.0"
Step2. Add it as your video play in xml layout.
<fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
android:id="#+id/videoPlayer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Step 3. Check from here how to use this library in your class,
public class PlayVideoActivity extends BaseActivity {
#BindView(R.id.videoPlayer)
JCVideoPlayerStandard mVideoPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreFromIntent(getIntent());
}
#Override
public int getLayout() {
return R.layout.activity_play_video;
}
// get video path from intent and play the video here
private void restoreFromIntent(Intent intent) {
mVideoPlayer.setUp("rtsp://192.168.1.143:8554/vid.mp4"
, JCVideoPlayerStandard.SCREEN_LAYOUT_LIST, "");
}
#Override
public void onBackPressed() {
if (JCVideoPlayer.backPress()) {
return;
}
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
JCVideoPlayer.releaseAllVideos();
}
}
Hope this will help you to fix your problem.Thanks
seeking is not work correctly in my code,
I can only seek exactly in first half of my files,
I tested with mp3 in {30min, 60min, 90min, 120min} and don't work, but with mp4 it's ok.
public class Player extends AsyncTask<Integer, Integer, Integer> implements
OnBufferingUpdateListener, OnCompletionListener, OnErrorListener {
private static MediaPlayer mp;
protected static Player PLAYER = null;
public Player(){
mp = Defined.mp;
mp.setOnBufferingUpdateListener(this);
mp.setOnCompletionListener(this);
mp.setOnErrorListener(this);
}
doInBackground:
#Override
protected Integer doInBackground(Integer... params) {
prepareFileToPlay();
mp.start();
startProgress();
return null;
}
prepare File:
protected void prepareFileToPlay(){
String url="http://192.168.1.2/test10.mp3"; //mp3 duration: 60min
mp.reset();
try {
mp.setDataSource(url);
mp.prepare();
publishProgress(PLAYING);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Play function:
public static void play(){
if(PLAYER != null) PLAYER.cancel(true);
PLAYER = new Player();
PLAYER.execute("");
}
seek function:
public static void seekTo(int time){
//mp.seekTo(time);
//mp.seekTo(mp.getDuration()-10000); //seekTo 59:50
//mp.seekTo(mp.getDuration()-60000); //seekTo 59:00
Log.v("player", "CurrentPosition: "+ mp.getCurrentPosition() + " Duration:"+ mp.getDuration()); //Duration: 60 min
}
I was checking my application in BlueStacks, but I understand that this issue is dedicated to BlueStacks and this is not a public issue and it's not important...
I have 5 songs which i need to play one after the other, and it must loop from the first song after finishing the 5th song.
How do I use the MediaPlayer to achieve this?
public class MediaPlayerExample extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
songs= new int[] {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
play();
}
private void play()
{
current_index = (current_index +1)% 4;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IllegalStateException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IOException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
}
}
Simple:
int[] songs = new int[]{R.raw.ab_hai_hamari_bari, R.raw.ab_khel_jamay_ga, R.raw.ab_khel_ke_dikha_psl_official_song, R.raw.chakka_choka_islamabad_united, R.raw.dil_dil_pakistan_junaid, R.raw.duniya_se_aagay, R.raw.hai_jazba_junoon_tho_himmat_na_haar, R.raw.hum_hain_pakistani_junaid, R.raw.jeet_ki_lagan, R.raw.jeetay_ga_pakistan_dedicate, R.raw.josh_e_junoon_pakistan_cricket, R.raw.karachi_kings_official, R.raw.lahore_qalandar_official, R.raw.multan_sultan_official, R.raw.peshawar_zalmi, R.raw.quetta_gladiator, R.raw.stand_up_for_the_champions};
you need to use CountDownTimer for this. CountDown timer has give you facility to do this one by one ::
MediaPlayer mp_xmPlayer2 = new MediaPlayer();
mp_xmPlayer2 = MediaPlayer.create(this, R.raw.bg_music_wav);
for(int i=0;i<5;i++)
{
CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
mp_xmPlayer2.start();
}
public void onFinish() {
//change music name
}
};
cntr_aCounter.start();
}