Recording and playing, but the sound is not coming? - android

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 .

Related

Trying to record from a microphone on the android phone

I am trying to record from the microphone and I built a code by trying some code snippets else where but nothing happens:
Here is the code, can someone tell me how to get this working.I am new to android coding.
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.util.Log;
import java.io.*;
import android.os.Environment;
public class MainActivity extends Activity {
public static final int SAMPLING_RATE = 44100;
public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
public static final int CHANNEL_IN_CONFIG = AudioFormat.CHANNEL_IN_MONO;
public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
public static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLING_RATE, CHANNEL_IN_CONFIG, AUDIO_FORMAT);
public static final String AUDIO_RECORDING_FILE_NAME = "recording.raw";
private static final String LOGTAG = "MyActivity";
private volatile boolean mStop = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
text.setText("Hello World, Ranjan");
setContentView(text);
}
/*public void run()
{
TextView text = new TextView(this);
text.setText(" hello smart mute");
}*/
//#Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
Log.v(LOGTAG, "Starting recordingā€¦");
byte audioData[] = new byte[BUFFER_SIZE];
AudioRecord recorder = new AudioRecord(AUDIO_SOURCE,
SAMPLING_RATE, CHANNEL_IN_CONFIG,
AUDIO_FORMAT, BUFFER_SIZE);
recorder.startRecording();
String filePath = Environment.getExternalStorageDirectory().getPath()
+ "/" + AUDIO_RECORDING_FILE_NAME;
BufferedOutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(filePath));
} catch (FileNotFoundException e) {
Log.e(LOGTAG, "File not found for recording ", e);
}
while (!mStop) {
int status = recorder.read(audioData, 0, audioData.length);
if (status == AudioRecord.ERROR_INVALID_OPERATION ||
status == AudioRecord.ERROR_BAD_VALUE) {
Log.e(LOGTAG, "Error reading audio data!");
return;
}
try {
os.write(audioData, 0, audioData.length);
} catch (IOException e) {
Log.e(LOGTAG, "Error saving recording ", e);
return;
}
}
try {
os.close();
recorder.stop();
recorder.release();
Log.v(LOGTAG, "Recording doneā€¦");
mStop = false;
} catch (IOException e) {
Log.e(LOGTAG, "Error when releasing", e);
}
}
}
Add these to your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Try the below code,it helps us to record,stop and play audio
public class MainActivity extends Activity {
Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}

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

Record video and over the video show time and date over the video

Hi does anybody knows how to record video in android and for example above the recording screen at the bottom show current time and date
Here is code that record video in surface view and store in sdcard and for date and time by This
package com.po;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class VideoRD extends Activity implements OnClickListener,
SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
public static final String TAG = "VIDEOCAPTURE";
String str_getValue ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Intent i1 = getIntent();
str_getValue = i1.getStringExtra("videoImagename");
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.surface);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (recording) {
try {
recorder.stop();
recorder.release();
recording = false;
Log.v(TAG, "Recording Stopped");
initRecorder();
prepareRecorder();
} catch (Exception e) {
// TODO: handle exception
}
} else {
try {
recording = true;
recorder.start();
button.setText("stop");
} catch (Exception e) {
// TODO: handle exception
}
}
}
});
}
private void initRecorder() {
try {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
// recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/audiometer/video/"+str_getValue+"");
recorder.setMaxDuration(1200000000); // 50 seconds
recorder.setMaxFileSize(22000000); // Approximately 5 megabytes
} catch (Exception e) {
// TODO: handle exception
}
}
private void prepareRecorder() {
try {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
}
public void onClick(View v) {
/*
* if (recording) { recorder.stop(); recorder.release(); recording =
* false; Log.v(TAG, "Recording Stopped"); initRecorder();
* prepareRecorder(); } else { recording = true; recorder.start(); }
*/
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
finish();
}
}

How to Record Voice in android?

I am trying to record the voice in android But it will create the .mp3 file on the path (sdcard/filename) But when i run this file it doesen't play because it doesn't record the voice.
Here is My code
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case(R.id.Button01):
try {
//audio.start();
startRecord();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
case(R.id.Button02):
//audio.stop();
stopRecord();
}
}
private void startRecord() throws IllegalStateException, IOException{
// recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); //ok so I say audio source is the microphone, is it windows/linux microphone on the emulator?
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile("/sdcard/Music/"+System.currentTimeMillis()+".amr");
recorder.prepare();
recorder.start();
}
private void stopRecord(){
recorder.stop();
//recorder.release();
}
}
Manifest file
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Refer to the Android Audio Capture documentation for recording audio and playing back the recorded audio.
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
public class AudioRecorder {
final MediaRecorder recorder = new MediaRecorder();
public final String path;
public AudioRecorder(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
public void playarcoding(String path) throws IOException {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.start();
mp.setVolume(10, 10);
}
}
if you searched google, you'll find this in their API Guides:
/*
* The application needs to have the permission to write to external storage
* if the output file is written to the external storage, and also the
* permission to record audio. These permissions must be set in the
* application's AndroidManifest.xml file, with something like:
*
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
* <uses-permission android:name="android.permission.RECORD_AUDIO" />
*
*/
package com.android.audiorecordtest;
import android.app.Activity;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import java.io.IOException;
public class AudioRecordTest extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTest() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
SOURCE
Offical Example link from Google
https://developer.android.com/guide/topics/media/mediarecorder.html#example
I suggest to only follow that one since its guaranteed to be up-to-date and secure.
Get manifests permission
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
MainActivity code
AudioRecorder audioRecorder = new AudioRecorder("Service/Record");
try {
audioRecorder.start();
Toast.makeText(this, "Start", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Log.i("RecordError", e.getMessage());
}
findViewById(R.id.stopButton).setOnClickListener(v -> {
try {
audioRecorder.stop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
});
AudioRecorder class code here:
public class AudioRecorder {
final MediaRecorder recorder = new MediaRecorder();
public final String path;
public AudioRecorder(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".mp3";
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
public void playarcoding(String path) throws IOException {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(sanitizePath(path));
mp.prepare();
mp.start();
mp.setVolume(10, 10);
}
}
*** Get the user permission when the activity will start. MANAGE_EXTERNAL_STORAGE permission and RECORD_AUDIO permission.

Categories

Resources