package z.x;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
public class AsdqweActivity extends Activity {
/** Called when the activity is first created. */
VideoView myVideoView;
TextView translation;
String SrcPath = "/sdcard/bunny.MP4",txtdisplay="";
Thread Thread1,Thread2;
Button tag;
int count=0,tstart=-1,tend=0;
AudioManager am;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myVideoView = (VideoView) findViewById(R.id.newVideoView);
translation= (TextView) findViewById(R.id.translation);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(myVideoView);
myVideoView.setMediaController(mediaController);
myVideoView.setKeepScreenOn(true);
Runnable runnable = new VideoPlayer();
Thread2= new Thread(runnable);
Thread2.start();
runnable = new CountDownRunner();
Thread1= new Thread(runnable);
Thread1.start();
runnable = new AudioPlayer();
Thread1= new Thread(runnable);
Thread1.start();
am =
tag = (Button) findViewById(R.id.start);
tag.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//how to change the text on the button????????
if(count%2==0)
{
tstart=myVideoView.getCurrentPosition();
System.out.println("tag starts here: "+ tstart);
myVideoView.pause();
tend=tstart+1000;
count++;
if((tstart+1000)>myVideoView.getDuration())
{
tend=myVideoView.getDuration();
count++;
}
}
else
{
tend = myVideoView.getCurrentPosition();
if(tend>=(tstart+1000)){
System.out.println("tag ends here: "+ tend);
count++;
myVideoView.pause();
}
else
{
System.out.println("invalid tagging");
}
tstart=-1;
}
}
});
myVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
Log.v("log_tag", "On Completion");
try {
Thread1.join();
Thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//r.stopThread();
finish();
}
});
}
class VideoPlayer implements Runnable{
public void run()
{
myVideoView.requestFocus();
myVideoView.setVideoPath(SrcPath);
myVideoView.start();
}
}
class AudioPlayer implements Runnable{
public AudioPlayer() {
// TODO Auto-generated constructor stub
}
public void run()
{
/*myVideoView.setsetvolume(0,0);
audio.requestFocus();
audio.setVideoPath(SrcPathaudio);
audio.start();*/
}
}
class CountDownRunner implements Runnable
{
File file = new File("/sdcard/harsh.srt");
long r=0;
RandomAccessFile rand;
public CountDownRunner() {
// TODO Auto-generated constructor stub
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try {
rand = new RandomAccessFile(file,"r");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
translation = (TextView)findViewById(R.id.translation);
}
public void run()
{
// Get the object of DataInputStream
while(!Thread.currentThread().isInterrupted())
{
try
{
doWork();
Thread.sleep(100);
}catch (InterruptedException e)
{
Thread.currentThread().interrupt();
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
closeRandFile();
}
public void closeRandFile(){
try {
rand.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doWork(){
runOnUiThread(new Runnable() {
public void run() {
try{
rand.seek(r);
//If it returns milliseconds, divide by 1000
int playTime = myVideoView.getCurrentPosition();
long t1=0,t2=0;
int i=0,j=0;
/* String textValue = "i havent entered it yet";
System.out.println(playTime);
if(playTime<15000){
textValue = "its still not 15000";
System.out.println(textValue);
}else if(playTime>3000)
{textValue = "its more than 15000";}*/
////////////////////////////////////
try{
// Open the file that is the first
// command line parameter
String strLine;
//Read File Line By Line
while(((strLine = rand.readLine()) != null)&&((strLine=="")))
{
System.out.println(strLine+" line 184");
}
if(strLine != null)
{
i = Integer.parseInt(strLine);
System.out.println(strLine+" line 189");
if(i>j){
if((strLine = rand.readLine()) != null)
{
//02:03:24,100 --> 02:03:25,500
//String substring(int startIndex, int endIndex)
int h =Integer.parseInt(strLine.substring(0,2));
int m =Integer.parseInt(strLine.substring(3,5));
int s =Integer.parseInt(strLine.substring(6,8));
int ms=Integer.parseInt(strLine.substring(9,12));
t1 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("start of this text time "+t1);
int l = strLine.indexOf("-->")+4;
h =Integer.parseInt(strLine.substring(l+0,l+2));
m =Integer.parseInt(strLine.substring(l+3,l+5));
s =Integer.parseInt(strLine.substring(l+6,l+8));
ms=Integer.parseInt(strLine.substring(l+9,l+12));
t2 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("end of this text time "+t2);
}
if((playTime<=t2)&&(playTime>=t1)){
while (((strLine = rand.readLine()) != null)&&(strLine!="")){
// Print the content on the console
txtdisplay=txtdisplay+strLine;
}
System.out.println(txtdisplay);
r=rand.getFilePointer();
translation.setText(txtdisplay);
}
txtdisplay="";
}
}
//Close the input stream
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
//////////////////////////////////////
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
I am new here. I was asked by my professor to play other audio while the same video is being played(for example a person doesn't understand English and wants the the app to play french ). I have used video view. One possible method was to mute the present audio and play the french audio stored in my sdcard. but video view supports no muting( i couldn't find one). I read that i have to go for media player instead of video view.
Please help...!! what should i do... Thanks in advance.
if you want to get access to the MediaPlayer of a VideoView you have to call MediaPlayer.OnPreparedListener and MediaPlayer.OnCompletionListener, then you can call setVolume(0f, 0f); function to set the volume to 0.
Do this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
VideoView videoView = (VideoView)this.findViewById(R.id.VVSimpleVideo);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
videoView.setMediaController(mc);
String _path = "/mnt/sdcard/Movies/video5.mp4";
videoView.setVideoPath(_path);
videoView.setOnPreparedListener(PreparedListener);
videoView.requestFocus();
//Dont start your video here
//videoView.start();
}
MediaPlayer.OnPreparedListener PreparedListener = new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer m) {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
m.setVolume(0f, 0f);
m.setLooping(false);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Related
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");
}
}
}
});
How to record audio and playing sound at the same time. Which process is better to implement in background and what to use Thread or AsyncTask? I haved tried playing sound in new thread and recordning on main thread but i have problem that on some devices i get error that the main thread is overload.
Is it better to use native rocordning, because i also need recorded buffer?
Does anybody have any example how to use native recording?
You can use following custom class:-
package com.app.controller;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.provider.SyncStateContract.Constants;
import android.widget.Toast;
public class MediaController implements OnPreparedListener{
public MediaController() {
// TODO Auto-generated constructor stub
}
public MediaPlayer mp;
public void getMediaPlayObject() {
try {
System.out.println("00000000000000");
mp = new MediaPlayer();
System.out.println("2222222222");
} catch (Exception e) {
// TODO: handle exception
System.out.println("exception in audia player====" + e.toString());
}
}
public void onPrepared(MediaPlayer player) {
mp.start();
}
boolean WORKING = true;
public void mediaPlayStart(final Context m_Context) {
try {
mp = new MediaPlayer();
mp.setDataSource(m_Context, Uri.parse(Contants.audioURL_OR_PATH));
mp.prepare();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setLooping(true);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(m_Context, "Service unavailable this time. Please try again!", Toast.LENGTH_LONG).show();
System.out.println("#####THE EXCEPTION IN THE MEDIA PLAYER PLAY==="+e.getMessage());
}
}
public void mediaPlayStop() {
try {
if (mp.isPlaying()) {
mp.stop();
}
} catch (Exception e) {
// TODO: handle exception
}
}
private static String getSoundPath(int countPositiong) {
// TODO Auto-generated method stub
String aa = "";
try {
if (countPositiong < 10) {
aa = "sounds/00" + countPositiong + ".mp4";
} else if (countPositiong < 100) {
aa = "sounds/0" + countPositiong + ".mp4";
} else {
aa = "sounds/" + countPositiong + ".mp4";
}
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("name is : " + aa);
return aa;
}
}
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();}
}
}
I use the following code to record audio files and play. I have a resume function which starts recording again. The audio files are stored in sdcard. My problem is, the files get stored in the sdcard but the file alone play. I need to play all the recorded files one after another. Give suggestions. I am running out of time...
ReadSDData.java
package com.fsp.audio;
import java.io.File;
import java.util.ArrayList;
import android.os.Environment;
import android.util.Log;
public class ReadSDDatas {
public String filePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String newPath=extstoredir+newFolderName;
return newPath;
}
public String getCombineFile()
{
String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
String audname="ComAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+"/"+audname+ext;
Log.d("Combined audio file",audpath);
return audpath;
}
public ArrayList<String> getFileNames()
{
ArrayList<String> names=new ArrayList<String>();
names.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
System.out.println("File Name======>>>"+files[i].getName());
names.add(files[i].getName().toString().trim());
}
}
return names;
}
public ArvrayList<String> getFullAudioPath()
{
ArrayList<String> fullPath=new ArrayList<String>();
fullPath.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
String fpath=path+File.separator+files[i].getName().toString().trim();
System.out.println("File Full Path======>>>"+fpath);
fullPath.add(fpath);
}
}
return fullPath;
}
}
AudioResume1.java
package com.fsp.audio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
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;
public class AudioResume1 extends Activity {
ArrayList<String> audNames=new ArrayList<String>();
ArrayList<String> audFullPath=new ArrayList<String>();
byte fileContent[];
Button record=null;
Button stoprec=null;
Button play=null;
public MediaPlayer player=null;
public MediaRecorder recorder=null;
int cou=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
record=(Button)findViewById(R.id.recBtn);
stoprec=(Button)findViewById(R.id.stopBtn);
play=(Button)findViewById(R.id.playBtn);
record.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stated Recording **********");
recorder=new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
String path=audioFilePath();
System.out.println("Recording Path===========>>>"+path);
recorder.setOutputFile(path);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try
{
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
stoprec.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stoped Recording **********");
recorder.stop();
recorder.release();
recorder=null;
}
});
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
getAudioNames();
readAudioAsStream();
}
});
}
public void readAudioAsStream()
{
getAudioPath();
File f;
FileInputStream ins = null;
ReadSDDatas rds=new ReadSDDatas();
try
{
String comfile=rds.getCombineFile();
//FileOutputStream fos=new FileOutputStream(comfile);
Log.d("combined file",comfile);
File file=new File(comfile);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
Log.d("path size",Integer.toString(audFullPath.size()));
for(int i=0;i<audFullPath.size();i++)
{
String filepath=audFullPath.get(i);
Log.d("Filepath",filepath);
f=new File(audFullPath.get(i));
fileContent = new byte[(int)f.length()];
ins=new FileInputStream(audFullPath.get(i));
int numofbytes=ins.read(fileContent);
System.out.println("Number Of Bytes Read===========>>>"+numofbytes);
raf.seek(file.length());
raf.write(fileContent);
}
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playAudio();
/*for(int i=0;i<audFullPath.size();i++)
{
Log.d("fullpathsize",Integer.toString(audFullPath.size()));
playAudio(audFullPath.get(i));
}*/
}
public void playAudio()
{
//Log.d("value of path",path);
/*String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String filename="ComAudio.3gp";
String path1=extstoredir+newFolderName+filename;
Log.d("path1",path1);*/
String path="/sdcard/MyComAudio/ComAudio.3gp";
player= new MediaPlayer();
try
{
player.setDataSource(path);
player.prepare();
player.start();
}
catch (IllegalArgumentException 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();
}
}
public void getAudioPath()
{
ReadSDDatas rds=new ReadSDDatas();
audFullPath=rds.getFullAudioPath();
}
public void getAudioNames()
{
ReadSDDatas rds=new ReadSDDatas();
audNames=rds.getFileNames();
}
public String audioFilePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
cou++;
String audname="RecAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+Integer.toString(cou)+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+File.separator+audname+Integer.toString(cou)+ext;
return audpath;
}
}
You can use MediaPlayer.onCompletionListener to listen to the event when a track ends, so that you can play the next one
UPDATE
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
player.stop();
// play next audio file
}
});
player.start();
UPDATE 2
Your code in the comment won't work, this could be a solution:
int i = 0;
//somewhere in your activity you start playing your first file
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
public void playAudio(path) {
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override public void onCompletion(MediaPlayer mp) {
player.stop();
if(i < numberOfFiles) {
i++;
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
} else i = 0;
}
});
player.start();
}
Yes this code will work fine but i have implemented differently and this will work more fine as given code
because if you play next file inside setOnCompletionListener method then it will call only single time i.e when playing first file it will call completion method and play another file but this time it will not call so you need to create new instance . dont worry just forget use
this
mc = new CountDownTimer(cownDownTime, 1000) {
public void onFinish() {
Log.i("call data hrer","aao bhai");
//initlize();
//updateText();
//startPlayProgressUpdater();
}
i.e play next file inside the Countdown timer finish() method it will run efficiently
I use the following code to record audio files and play. I have a resume function which starts recording again. The audio files are stored in sdcard. My problem is, the files get stored in the sdcard but the file alone play. I need to play all the recorded files one after another. Give suggestions. I am running out of time...
ReadSDData.java
package com.fsp.audio;
import java.io.File;
import java.util.ArrayList;
import android.os.Environment;
import android.util.Log;
public class ReadSDDatas {
public String filePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String newPath=extstoredir+newFolderName;
return newPath;
}
public String getCombineFile()
{
String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
String audname="ComAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+"/"+audname+ext;
Log.d("Combined audio file",audpath);
return audpath;
}
public ArrayList<String> getFileNames()
{
ArrayList<String> names=new ArrayList<String>();
names.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
System.out.println("File Name======>>>"+files[i].getName());
names.add(files[i].getName().toString().trim());
}
}
return names;
}
public ArvrayList<String> getFullAudioPath()
{
ArrayList<String> fullPath=new ArrayList<String>();
fullPath.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
String fpath=path+File.separator+files[i].getName().toString().trim();
System.out.println("File Full Path======>>>"+fpath);
fullPath.add(fpath);
}
}
return fullPath;
}
}
AudioResume1.java
package com.fsp.audio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
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;
public class AudioResume1 extends Activity {
ArrayList<String> audNames=new ArrayList<String>();
ArrayList<String> audFullPath=new ArrayList<String>();
byte fileContent[];
Button record=null;
Button stoprec=null;
Button play=null;
public MediaPlayer player=null;
public MediaRecorder recorder=null;
int cou=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
record=(Button)findViewById(R.id.recBtn);
stoprec=(Button)findViewById(R.id.stopBtn);
play=(Button)findViewById(R.id.playBtn);
record.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stated Recording **********");
recorder=new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
String path=audioFilePath();
System.out.println("Recording Path===========>>>"+path);
recorder.setOutputFile(path);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try
{
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
stoprec.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stoped Recording **********");
recorder.stop();
recorder.release();
recorder=null;
}
});
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
getAudioNames();
readAudioAsStream();
}
});
}
public void readAudioAsStream()
{
getAudioPath();
File f;
FileInputStream ins = null;
ReadSDDatas rds=new ReadSDDatas();
try
{
String comfile=rds.getCombineFile();
//FileOutputStream fos=new FileOutputStream(comfile);
Log.d("combined file",comfile);
File file=new File(comfile);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
Log.d("path size",Integer.toString(audFullPath.size()));
for(int i=0;i<audFullPath.size();i++)
{
String filepath=audFullPath.get(i);
Log.d("Filepath",filepath);
f=new File(audFullPath.get(i));
fileContent = new byte[(int)f.length()];
ins=new FileInputStream(audFullPath.get(i));
int numofbytes=ins.read(fileContent);
System.out.println("Number Of Bytes Read===========>>>"+numofbytes);
raf.seek(file.length());
raf.write(fileContent);
}
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playAudio();
/*for(int i=0;i<audFullPath.size();i++)
{
Log.d("fullpathsize",Integer.toString(audFullPath.size()));
playAudio(audFullPath.get(i));
}*/
}
public void playAudio()
{
//Log.d("value of path",path);
/*String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String filename="ComAudio.3gp";
String path1=extstoredir+newFolderName+filename;
Log.d("path1",path1);*/
String path="/sdcard/MyComAudio/ComAudio.3gp";
player= new MediaPlayer();
try
{
player.setDataSource(path);
player.prepare();
player.start();
}
catch (IllegalArgumentException 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();
}
}
public void getAudioPath()
{
ReadSDDatas rds=new ReadSDDatas();
audFullPath=rds.getFullAudioPath();
}
public void getAudioNames()
{
ReadSDDatas rds=new ReadSDDatas();
audNames=rds.getFileNames();
}
public String audioFilePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
cou++;
String audname="RecAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+Integer.toString(cou)+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+File.separator+audname+Integer.toString(cou)+ext;
return audpath;
}
}
You can use MediaPlayer.onCompletionListener to listen to the event when a track ends, so that you can play the next one
UPDATE
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
player.stop();
// play next audio file
}
});
player.start();
UPDATE 2
Your code in the comment won't work, this could be a solution:
int i = 0;
//somewhere in your activity you start playing your first file
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
public void playAudio(path) {
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override public void onCompletion(MediaPlayer mp) {
player.stop();
if(i < numberOfFiles) {
i++;
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
} else i = 0;
}
});
player.start();
}
Yes this code will work fine but i have implemented differently and this will work more fine as given code
because if you play next file inside setOnCompletionListener method then it will call only single time i.e when playing first file it will call completion method and play another file but this time it will not call so you need to create new instance . dont worry just forget use
this
mc = new CountDownTimer(cownDownTime, 1000) {
public void onFinish() {
Log.i("call data hrer","aao bhai");
//initlize();
//updateText();
//startPlayProgressUpdater();
}
i.e play next file inside the Countdown timer finish() method it will run efficiently