Mp3 Song does not play in MediaPlayer - android

In my application, in MediaPlayer online song does not play . It goes in preparing state. I have put my code.When it run on emulator, it gives black screen that means it should be in wait mode.
I have use much ways for playing song but it couldn't play.When I use debugger and when mediaplayer goes prepare() state, it should come black screen no any output screen on logcat or anywhere else.
My code is as following:
package com.yeshuduniya;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.Model.GallryModel;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.os.PowerManager.WakeLock;
public class Songs_Player extends Activity implements OnClickListener ,OnCompletionListener
{
Uri uri;
URL url;
private MediaPlayer mediaPlayer = null;
private boolean isPlaying = false;
private String song_url;
Handler seekHandler = new Handler();
TextView txt_song_name;
private static int classID = 579; // just a number
SeekBar seek_bar;
WakeLock wakeLock;
ProgressDialog progressDialogue;
private static final String[] EXTENSIONS = { ".mp3", ".mid", ".wav", ".ogg", ".mp4" }; //Playable Extensions
List<String> trackArtworks; //Track artwork names
ImageView bg; //Track artwork
Button btn_Play,btn_prev,btn_next; //The play button will need to change from 'play' to 'pause', so we need an instance of it
int currentTrack; //index of current track selected
int type; //0 for loading from assets, 1 for loading from SD card
ArrayList<GallryModel> songList;
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_songs__player);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//setVolumeControlStream(AudioManager.STREAM_MUSIC);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Lexiconda");
setUI();
Intent mIntent = getIntent();
songList=(ArrayList<GallryModel>) mIntent.getSerializableExtra("SongsList");
currentTrack = mIntent.getIntExtra("position", 0);
if(savedInstanceState ==null)
{
mediaPlayer=((YeshuDuniaApplication) Songs_Player.this.getApplication()).medaiplayer;
if(mediaPlayer.isPlaying())
{
stop();
playTrack(currentTrack);
}
else
{
playTrack(currentTrack);
//Toast.makeText(getBaseContext(), "Loaded " + Integer.toString(songList.size()) + " Tracks", Toast.LENGTH_SHORT).show();
}
//play(songList.get(currentTrack).getImage());
btn_Play.setBackgroundResource(R.drawable.pause);
}
btn_next.setOnClickListener(this);
btn_prev.setOnClickListener(this);
btn_Play.setOnClickListener(this);
}
private void setUI()
{
//seek_bar = (SeekBar) findViewById(R.id.seek_bar);
btn_next=(Button)findViewById(R.id.btn_mgallary_next);
btn_prev=(Button)findViewById(R.id.btn_mgallary_previous);
btn_Play=(Button)findViewById(R.id.btn_mgallary_Play);
bg = (ImageView) findViewById(R.id.bg);
txt_song_name=(TextView)findViewById(R.id.txt_song_name);
}
// Runnable run = new Runnable() {
//
// #Override
// public void run() {
// seekUpdation();
// }
// };
// public void seekUpdation() {
//
// seek_bar.setProgress(mediaPlayer.getCurrentPosition());
// seekHandler.postDelayed(run, 1000);
// }
#Override
public void onResume(){
super.onResume();
wakeLock.acquire();
}
//Play Songs.
#SuppressWarnings("deprecation")
public void play(int currentTrack) throws MalformedURLException
{ this.currentTrack=currentTrack;
System.out.println("Playiong track is"+currentTrack);
this.song_url=songList.get(currentTrack).getSongUrl();
if (!isPlaying)
{
/*
try {
if(URLUtil.isValidUrl(song_url) || Patterns.WEB_URL.matcher(song_url).matches()) {
song_url = URLEncoder.encode(song_url,"UTF-8");
url = new URL(song_url);
// so on
} else {
Toast.makeText(getBaseContext(), "Please enter valid URL.", Toast.LENGTH_SHORT).show();
} */
isPlaying = true;
btn_Play.setBackgroundResource(R.drawable.pause);
try {
url = new URL(song_url);
mediaPlayer.setLooping(false);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
uri = Uri.parse(url.toURI().toString());
mediaPlayer.setDataSource(uri.toString());
//mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(this);
// When song is ended then media player automatically called onCompletion method.
}
catch (MalformedURLException e)
{
btn_Play.setBackgroundResource(R.drawable.play);
isPlaying=false;
Toast.makeText(getBaseContext(), "File is not mp3 supported", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IllegalArgumentException e)
{
btn_Play.setBackgroundResource(R.drawable.play);
isPlaying=false;
Toast.makeText(getBaseContext(), "File is not mp3 supported", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (SecurityException e)
{
btn_Play.setBackgroundResource(R.drawable.play);
isPlaying=false;
Toast.makeText(getBaseContext(), "File is not mp3 supported", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IllegalStateException e)
{
btn_Play.setBackgroundResource(R.drawable.play);
isPlaying=false;
Toast.makeText(getBaseContext(), "File is not mp3 supported", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e)
{
btn_Play.setBackgroundResource(R.drawable.play);
isPlaying=false;
Toast.makeText(getBaseContext(), "File is not mp3 supported", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch (URISyntaxException e1)
{
btn_Play.setBackgroundResource(R.drawable.play);
isPlaying=false;
Toast.makeText(getBaseContext(), "File is not mp3 supported", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
}
else
{
stop();
play(currentTrack);
}
}
//Stop song.
public void stop()
{
synchronized(this)
{
isPlaying = false;
if (mediaPlayer != null)
{
mediaPlayer.reset();
}
//stopForeground(true);
}
}
//Pause song.
public void pause()
{
if (isPlaying) {
isPlaying = false;
if (mediaPlayer != null)
{
mediaPlayer.pause();
mediaPlayer = null;
}
}
}
#Override
public void onPause()
{
super.onPause();
wakeLock.release();
}
//Generate a String Array that represents all of the files found
//Plays the Track
public void playTrack(int currentTrack)
{
this.currentTrack=currentTrack;
//this.song_url=currentTrack;
if(!isPlaying )
{
try {
play(currentTrack);
Toast.makeText(Songs_Player.this, "Playing " + songList.get(currentTrack).getSongTitle(), Toast.LENGTH_SHORT).show();
} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onClick(View v)
{ boolean flag=false;
switch(v.getId())
{
case R.id.btn_mgallary_Play:
synchronized(this){
if(isPlaying)
{
isPlaying = false;
if (mediaPlayer != null)
{
mediaPlayer.pause();
}
btn_Play.setBackgroundResource(R.drawable.play);
}
else
{
isPlaying = true;
mediaPlayer.start();
btn_Play.setBackgroundResource(R.drawable.pause);
//playTrack(songList.get(currentTrack).getImage());
}
}
return;
case R.id.btn_mgallary_previous:
stop();
if(currentTrack == 0)
{
isPlaying=false;
currentTrack=songList.size()-1;
playTrack(currentTrack);
}
else
{
isPlaying=false;
currentTrack=currentTrack-1;
btn_Play.setBackgroundResource(R.drawable.play);
playTrack(currentTrack);
}
return;
case R.id.btn_mgallary_next:
stop();
if(currentTrack == songList.size()-1)
{
isPlaying=false;
currentTrack=0;
btn_Play.setBackgroundResource(R.drawable.play);
playTrack(currentTrack);
}
else
{
isPlaying=false;
btn_Play.setBackgroundResource(R.drawable.play);
currentTrack=currentTrack+1;
playTrack(currentTrack);
}
return;
default:
return;
}
}
#Override
public void onCompletion(MediaPlayer mediaPlayer)
{
mediaPlayer.stop();
mediaPlayer.reset();
if(currentTrack != songList.size()-1)
{ isPlaying=false;
currentTrack=currentTrack+1;
btn_Play.setBackgroundResource(R.drawable.play);
playTrack(currentTrack);
}
else
{ if(currentTrack == 0)
{
isPlaying=false;
currentTrack=songList.size()-1;
btn_Play.setBackgroundResource(R.drawable.play);
playTrack(currentTrack);
}
else
{
if(currentTrack == songList.size()-1)
{
isPlaying=false;
currentTrack=0;
btn_Play.setBackgroundResource(R.drawable.play);
playTrack(currentTrack);
}
}
}
}
}
I have used URLEncoder for removing spaces but it should give no url found. my song url's are play on browser. So Plz give me suggestion.
My e.g. url is,
http://www.yeshuduniya.com/admin/yeshuDuniyaMusic/34_Prabhu tu mahan/34_Prabhu tu mahan.mp3
http://www.yeshuduniya.com/admin/yeshuDuniyaMusic/bhoole_aur_bhatke_they_hum/14_bhoole_aur_bhatke_they_hum.mp3

Related

Android media sound Recorder Start failed

My application got crashed whenever i press start button. Logcat says its because of start method failed. I google the error but i didn't find anything. It is giving exception at the native method Start(v);
Here is my logcat :
08-22 18:44:23.420: E/MediaRecorder(3607): start failed: -2147483648
08-22 18:44:23.420: V/MediaRecorderJNI(3607): process_media_recorder_call
08-22 18:44:23.420: W/dalvikvm(3607): threadid=1: thread exiting with uncaught exception (group=0x41234438)
08-22 18:44:23.420: E/AndroidRuntime(3607): FATAL EXCEPTION: main
08-22 18:44:23.420: E/AndroidRuntime(3607): java.lang.RuntimeException: start failed.
Here is my Code :
import java.io.File;
import java.io.IOException;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private File outputFile = null;
private AudioTrack mAudioTrack;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private Spinner sp;
private TextView text;
public SoundPool spl;
public int explosion = 0;
private Button playMod;
private int sampleRate = 8000;
private Uri newUri;
AudioManager audioManager;
int counter;
float actVolume, maxVolume, volume;
boolean loaded = false;
private static final String TAG = "SoundRecordingActivity";
String [] singers = {"Atif Aslam" , "Arijit Singh" , "Shreya Goshal"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);
sp = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,singers);
adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp.setAdapter(adp);
// store it to sd card
//outFile = Environment.getExternalStorageDirectory().
// getAbsolutePath() + "/AudioRecord.3gpp";
File sampleDir = Environment.getExternalStorageDirectory();
try {
outputFile = File.createTempFile("sound", ".m4a", sampleDir);
} catch (IOException e) {
Toast.makeText(this, "No Memory Card Inserted", Toast.LENGTH_LONG).show();
Log.e(TAG, "sdcard access error");
return;
}
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile.getAbsolutePath());
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stop(v);
}
});
playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});
stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
playMod = (Button)findViewById(R.id.button1);
playMod.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
playModified(v);
}
});
}
public void start(View view){
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
/////////////////////////////////////
// addRecordingToMediaLibrary();
//////////////////////////////////////
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile.getAbsolutePath());
myPlayer.prepare();
myPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You save the temporary file as type, m4a:
outputFile = File.createTempFile("sound", ".m4a", sampleDir);
but you have the wrong output format (3gp):
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
Solution:
If you'd like to save the recorded file as a 3gp format, you'd have to save the file as:
outputFile = File.createTempFile("sound", ".3gp", sampleDir);
else, If you'd like to save as an m4a format, you'd have to change the output format as follows:
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
Here's a list of the available formats
I had the same problem. Because I also have MediaPlayer, I solve this problem by the code:
mediaPlayer.setAudioStreamType(AudioManager.ADJUST_LOWER);
this solve my problem.

Open video file from File Explorer and playing in my videoplayer activity

I have my VideoPlayerActivity.java and I want to open when I press on a video file from my sdcard through my file explore or another application
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.TextView;
import android.widget.Toast;
public class VideoPlayerActivity extends Activity implements OnErrorListener, OnBufferingUpdateListener,
OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener,
MediaPlayerControl, SurfaceHolder.Callback, VideoControllerView.MediaPlayerControl, Runnable {
private static final String TAG = "Player";
MediaPlayer mediaPlayer;
SurfaceHolder surfaceHolder;
SurfaceView playerSurfaceView;
VideoControllerView controller;
private int position;
private String videoPath;
int videoWidth, videoHeight;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.video_player);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
videoPath = getIntent().getStringExtra("videoPath");
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
controller = new VideoControllerView(this);
try {
// String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
/* final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path.equals(current) && mediaPlayer != null) {
mediaPlayer.start();
return;
}
current = path;*/
// Uri fileUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 166);
// Uri uri = MediaStore.Files.getContentUri("external");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.prepareAsync();
mediaPlayer.setScreenOnWhilePlaying(true);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
Intent intent = new Intent();
intent.setClass(VideoPlayerActivity.this, MainActivity.class);
startActivity(intent);
}
});
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(videoPath);
mediaPlayer.prepare();
Log.v(TAG, "Duration: ===>" + mediaPlayer.getDuration());
mediaPlayer.start();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
wifiLock.release();
} /*catch (Exception e) {
Log.e(TAG, "error: "+ e.getMessage(), e);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}*/
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(path);
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
private final Handler handler = new Handler (){
#Override
public void handleMessage(Message msg) {
final int currentPos = msg.getData().getInt("CurrentPosition");
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
/*if(controller.isShowing()) {
controller.hide();
}else {
controller.show();
}*/
return false;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
mediaPlayer.start();
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public boolean isFullScreen() {
return false;
}
#Override
public void toggleFullScreen() {
}
// End VideoMediaController.MediaPlayerControl
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
videoWidth = width;
videoHeight = height;
Toast.makeText(getApplicationContext(),
String.valueOf(videoWidth) + "x" + String.valueOf(videoHeight),
Toast.LENGTH_SHORT).show();
if (mediaPlayer.isPlaying()){
surfaceHolder.setFixedSize(videoWidth, videoHeight);
}
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void run() {
// TODO Auto-generated method stub
controller = new VideoControllerView(this);
try {
mediaPlayer.setDataSource(videoSrc);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
/*
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt("CurrentPosition", mediaPlayer.getCurrentPosition());
msg.setData(bundle);
handler.sendMessage(msg);
// handler.postDelayed(callBack, 500);*/
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
And my logcat error is
01-03 20:42:14.881: V/MediaPlayer(14737): setVideoSurfaceTexture
01-03 20:42:14.881: W/System.err(14737): java.lang.NullPointerException: uriString
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:468)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:458)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri.parse(Uri.java:430)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1256)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1221)
My XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:keepScreenOn="true"
android:id="#+id/video_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/videoSurfaceContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SurfaceView
android:id="#+id/playersurface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
</LinearLayout>
And one more question. I have this public void method for streaming
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(path);
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
How can I used to stream files from another application program?
When I play video from main activity it plays and when I quit and go to file explorer and chose my player from custom dialog box and open I have that problem with uriString...
When navigating through your files you can set a clicklistener on a thumbnail. I use this code to fire up a full-screen video editor:
thumbNail.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (pathType.equals("image")) {
<snip>
}
else {
// music file
}
else {
// must be video
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(cmsURL + pathListFull,"video/mp4");
PackageManager packageManager = getActivity().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivity(intent);
}
else {
Log.d("SHOWFILE", "no intents available");
}
}
}
});

Cannot play mp4 video

I am trying to make a video player in android.
It plays the 3GP format videos.
But it does not support the mp4 video.Below is my code in android for the same.Why does it not support the mp4 format on the device and emulator?
package com.example.videoplayer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoViewDemo extends Activity {
private static final String TAG = "VideoViewDemo";
private VideoView mVideoView;
private EditText mPath;
private ImageButton mPlay;
private ImageButton mPause;
private ImageButton mReset;
private ImageButton mStop;
private String current;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
mVideoView = (VideoView) findViewById(R.id.surface_view);
mPath = (EditText) findViewById(R.id.path);
mPath.setText("ooklnet.com/files/368/368007/video.mp4");
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mReset = (ImageButton) findViewById(R.id.reset);
mStop = (ImageButton) findViewById(R.id.stop);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
playVideo();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mVideoView != null) {
mVideoView.pause();
}
}
});
mReset.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mVideoView != null) {
mVideoView.seekTo(0);
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mVideoView != null) {
current = null;
mVideoView.stopPlayback();
}
}
});
/*runOnUiThread(new Runnable(){
public void run() {
sleep(2000);
playVideo();
}
});*/
Thread _trd1 = new Thread() {
public void run() {
try {
sleep(2000);
runOnUiThread(new Runnable() {
public void run() {
playVideo();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
_trd1.start();
// new DoBackgroundTask().execute();
}
public class DoBackgroundTask extends AsyncTask
<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
protected String doInBackground(String... locationNames) {
playVideo();
return null;
}
protected void onPostExecute(String addresses){
}
}
private void playVideo() {
try {
final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path == null || path.length() == 0) {
Toast.makeText(VideoViewDemo.this, "File URL/path is empty",
Toast.LENGTH_LONG).show();
} else {
// If the path has not changed, just start the media player
if (path.equals(current) && mVideoView != null) {
mVideoView.start();
mVideoView.requestFocus();
return;
}
current = path;
mVideoView.setVideoPath(getDataSource("ooklnet.com/files/368/368007/video.mp4"));
mVideoView.start();
mVideoView.requestFocus();
}
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
if (mVideoView != null) {
mVideoView.stopPlayback();
}
}
}
private String getDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
return path;
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
temp.deleteOnExit();
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[128];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
return tempPath;
}
}
}
Please advise as soon as possible.
Thanks.
The problem might be with the video encoding. Android Froyo and Gingerbread doesn't support H264 formats other than "Baseline" H264. So if your video is Mp4 & H264 encoded make sure its "AVC baseline" encoded. Use some tools like "Media info" in windows/Linux and check your video encoding. Convert the video to Baseline if possible.
An alternative workaround is to skip the Videoview and use a video play intent and redirect the playback to an app. User will be prompted to pick a player to handle the playback. Obviously if the video view cant play the file, the default player also wont be able to handle the file. you can choose some other installed player like Mx-Player which will stream the file perfectly.
Hope that solved your issue.
Try correct video url with protocol: http://www.ooklnet.com/files/368/368007/video.mp4

Media player not running

I am trying to run a mp3 file using media player.It compiles fine,but it is not playing the mp3 file.Even when i checked the isPlaying(),it returns false. Please tell me what is the problem with it. This is the code:
package com.example.soundplayer;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
/**
* Variables
*/
MediaPlayer mp = null;
String hello = "Hello!";
String goodbye = "GoodBye!";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Talking with the buttonHello
*/
final Button buttonHello = (Button) findViewById(R.id.idHello);
buttonHello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
managerOfSound(hello);
} // END onClick()
}); // END buttonHello
}
/**
* Manager of Sounds
*/
protected void managerOfSound(String theText) {
mp = MediaPlayer.create(MainActivity.this, R.raw.sound);
mp = new MediaPlayer();
if (theText.equals(hello))
{
MediaPlayer.create(this, R.raw.sound);
mp.setVolume(1.0F, 1.0F);
mp.reset();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mp != null) {
mp.start();
}
if(mp.isPlaying()== true){
Toast.makeText(this, "mp is playing ", Toast.LENGTH_LONG).show();}
}
}
}
try below code
protected void managerOfSound(String theText) {
mp = MediaPlayer.create(MainActivity.this, R.raw.sound);
mp.setVolume(1.0F, 1.0F);
if (theText.equals(hello))
{
if (mp != null) {
mp.start();
}
if(mp.isPlaying()== true){
Toast.makeText(this, "mp is playing ", Toast.LENGTH_LONG).show();}
}
}

Recording and playing, but the sound is not coming?

package com.Project_recording;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Project_recordingActivity extends Activity {
private static final String APP_TAG = "com.hascode.android.soundrecorder";
private MediaRecorder recorder = new MediaRecorder();
private MediaPlayer player = new MediaPlayer();
private Button btRecord;
private Button btPlay;
private TextView resultView;
private boolean recording = false;
private boolean playing = false;
private File outfile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultView = (TextView) findViewById(R.id.output);
try {
// the soundfile
File storageDir = new File(Environment
.getExternalStorageDirectory(), "com.hascode.recorder");
storageDir.mkdir();
Log.d(APP_TAG, "Storage directory set to " + storageDir);
outfile = File.createTempFile("hascode", ".3gp", storageDir);
// init recorder
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outfile.getAbsolutePath());
// init player
player.setDataSource(outfile.getAbsolutePath());
} catch (IOException e) {
Log.w(APP_TAG, "File not accessible ", e);
} catch (IllegalArgumentException e) {
Log.w(APP_TAG, "Illegal argument ", e);
} catch (IllegalStateException e) {
Log.w(APP_TAG, "Illegal state, call reset/restore", e);
}
btRecord = (Button) findViewById(R.id.btRecord);
btRecord.setOnClickListener(handleRecordClick);
btPlay = (Button) findViewById(R.id.btPlay);
btPlay.setOnClickListener(handlePlayClick);
}
private final OnClickListener handleRecordClick = new OnClickListener() {
#Override
public void onClick(View view) {
if (!recording) {
startRecord();
} else {
stopRecord();
}
}
};
private final OnClickListener handlePlayClick = new OnClickListener() {
#Override
public void onClick(View view) {
if (!playing) {
startPlay();
} else {
stopPlay();
}
}
};
private void startRecord() {
Log.d(APP_TAG, "start recording..");
printResult("start recording..");
try {
recorder.prepare();
recorder.start();
recording = true;
} catch (IllegalStateException e) {
Log
.w(APP_TAG,
"Invalid recorder state .. reset/release should have been called");
} catch (IOException e) {
Log.w(APP_TAG, "Could not write to sd card");
}
}
private void stopRecord() {
Log.d(APP_TAG, "stop recording..");
printResult("stop recording..");
recorder.stop();
recorder.reset();
recorder.release();
recording = false;
}
private void startPlay() {
Log.d(APP_TAG, "starting playback..");
printResult("start playing..");
try {
playing = true;
player.prepare();
player.start();
} catch (IllegalStateException e) {
Log.w(APP_TAG, "illegal state .. player should be reset");
} catch (IOException e) {
Log.w(APP_TAG, "Could not write to sd card");
}
}
private void stopPlay() {
Log.d(APP_TAG, "stopping playback..");
printResult("stop playing..");
player.stop();
player.reset();
player.release();
playing = false;
}
private void printResult(String result) {
resultView.setText(result);
}
}
When I press the record button, Is starts recording. When I press the play button, It starting playing. When I again press the play button, I stops playing. The important issue which I am facing is the sound is not heared..? Please do me a needful. I am new to android..
Why you are resetting the recorder object immediately after recording .

Categories

Resources