Media player not running - android

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();}
}
}

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.

Mp3 Song does not play in MediaPlayer

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

Android playing audio and recordning audio at the same time

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;
}
}

send audio file to server after recording in android

Thanks in advance for spent Ur time on my app...
I have an application in which I require to create an audio file after clicking ona button named "RECORD" and send this file to server. The audio file must be send in any android supported audio format.
How can I achieve this...
Code For Recording in Android
main.java:
package com.example.audiosend;
import android.os.Bundle;
import android.app.Activity;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private String outputFile = null;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/MyAppRecording.3gpp"; //this is the folder in which your Audio file willl save
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
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);
}
});
}
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();
} 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);
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();
}
}

muting one audio and playing other audio in its place (VideoView)

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();
}
}
};

Categories

Resources