I'd written an application for playing 20 millisecond audio clip(.wav format).
It simply plays the sound clip repeatedly 1000 times.
But due to Latency, number of times it plays lies between 978 and 984. I'd also tried other audio format(.ogg, .mp3, etc).
I want reduce the latency and also to get reliable number.
I'm sharing my code below:
package com.abhinav.soundlooper;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button btnStart;
TextView tvPause, tvLoop;
EditText etPause, etLoop;
long pause, loop;
private CountDownTimer timer;
MediaPlayer mp;
public Thread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
// tvLoop = (TextView) findViewById(R.id.etLoop)
etPause = (EditText) findViewById(R.id.etPause);
etLoop = (EditText) findViewById(R.id.etLoop);
btnStart.setOnClickListener(this);
mp = MediaPlayer.create(getApplicationContext(), R.raw.beepwav);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
// pause = Integer.valueOf(etPause.getText().toString()) + 1 ;
// loop = 1 + Integer.valueOf(etLoop.getText().toString());
// long ti = (pause+30);
// long tt = ti*loop;
timer = new CountDownTimer(30000, 30) {
int i =0;
public void onTick(long millisUntilFinished) {
// v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
mp.start();
// try {
// timer.wait(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
i++;
}
public void onFinish() {
// mTextField.setText("done!");
Log.i("loop", ""+i);
stopAll();
// mp.stop();
// mp.release();
}
}.start();
//
}
protected void stopAll() {
// TODO Auto-generated method stub
timer.cancel();
}
}
I'm not sure but if 1000 milliseconds is 1 second. So 30,000 milliesconds is 30 seconds.
and if the audio is 20 milliseconds then 30,000/20 is 1,500. So the audio is capable of being played 1.5K in 30 seconds.
timer = new CountDownTimer(30000, 27) {
int i =0;
public void onTick(long millisUntilFinished) {
// v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
mp.start();
// try {
// timer.wait(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
i++;
}
if with the 30 latency it's 950 times, what happens if we lower the latency to about 27?
and you can always you if statement ..
if (i == 1000){
stopAll();
} else {
i++
}
Related
I have songs from json in list view, and a play button in each row , after clicking on play Button my app freezes and App not responding dialog box comes, Sometime media player started after freezing sometimes its crashes. Because of App not responsive. This is my Code :
viewHolder.playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = position;
if (selectedPosition != mPlayingPosition) {
try {
mPlayerforplanet.reset();
mPlayerforplanet.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayerforplanet.setDataSource(song_urls);
logger.addRecordToLog("MediaPlayer audio session ID: " + mPlayerforplanet.getAudioSessionId());
logger.addRecordToLog("Media Player started " + "Started !");
mPlayerforplanet.prepare();
mPlayerforplanet.start();
} catch (IOException e) {
e.printStackTrace();
}
// playSongs(position);(i also try with method of playsong but no luck)
Toast.makeText(getContext(), "play song" + mPlayingPosition, Toast.LENGTH_SHORT).show();
}}});
Log cat after click on play button
01-10 07:13:33.501 17284-17293/luck.materialdesign.tabsnavigator I/art: Thread[5,tid=17293,WaitingInMainSignalCatcherLoop,Thread*=0xab8d8600,peer=0x12c000a0,"Signal Catcher"]: reacting to signal 3
01-10 07:13:34.273 17284-17293/luck.materialdesign.tabsnavigator I/art: Wrote stack traces to '/data/anr/traces.txt'
Please use prepareAsync instead of prepare and handle onPrepared and trigger start from there .
mPlayerforplanet.prepareAsync();
public void onPrepared(MediaPlayer mp) {
mPlayerforplanet.start;
}
sample code :
package com.example.simplemediaplayer.app;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.IOException;
public class MediaPlayerActivity extends ActionBarActivity {
private static final String TAG = "tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
String url = "http://www.brothershouse.narod.ru/music/pepe_link_-_guitar_vibe_113_club_mix.mp3"; // your URL here
MediaPlayer myMediaPlayer = new MediaPlayer();
myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
myMediaPlayer.setDataSource(url);
myMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
} catch (IOException e) {
Toast.makeText(this, "mp3 not found", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//mp3 will be started after completion of preparing...
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.media_player, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
For seek-bar use a anew runnable :
Starting runnable ,
public void onPrepared(MediaPlayer player) {
mPlayerforplanet.start();
mUpdateSeekBar.run();
}
Code in runnable
private final Runnable mUpdateSeekBar = new Runnable() {
#Override
public void run() {
int elapsedtime = mPlayerforplanet.getCurrentPosition();
/* update UI with getCurrentPosition*/
mHandler.postDelayed(mUpdateSeekBar, 1000);
}
};
i have made a countdown timer using progressbar and a thread,Now i want to stop the progress at the same time when user clicks on a button.I have tried thread.stop(),but it says there is .no such method,I have tried interruot method too with no luck,So can any buddy please help me by viewing my code.My code is as below:
code
package com.amar.lyricalgenius;
import com.amar.lyricalgenius.LoadingActivity.MyCountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class SinglePlayerOption extends Activity implements OnClickListener {
// visible gone
private int progressStatus = 0;
private Handler handler = new Handler();
Intent i;
TextView text_player_second;
ImageView vs_word;
ImageView player_second_pic, player_second_box;
ImageButton red_point1;
TextView text_number_pt1;
TextView text_number1;
ProgressBar pg_loading;
private CountDownTimer countDownTimer;
TextView timer_text;
private final long startTime = 8 * 1000;
private final long interval = 1 * 1000;
Button opt_1, opt_2, opt_3, opt_4;
Thread splashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.single_player_option);
init();
}
private void init() {
// TODO Auto-generated method stub
text_player_second = (TextView) findViewById(R.id.text_player_second);
vs_word = (ImageView) findViewById(R.id.vs_word);
player_second_pic = (ImageView) findViewById(R.id.player_second_pic);
player_second_box = (ImageView) findViewById(R.id.player_second_box);
red_point1 = (ImageButton) findViewById(R.id.red_point1);
text_number_pt1 = (TextView) findViewById(R.id.text_number_pt1);
text_number1 = (TextView) findViewById(R.id.text_number1);
opt_1 = (Button) findViewById(R.id.option_1);
opt_2 = (Button) findViewById(R.id.option_2);
opt_3 = (Button) findViewById(R.id.option_3);
opt_4 = (Button) findViewById(R.id.option_4);
opt_1.setOnClickListener(this);
opt_2.setOnClickListener(this);
opt_3.setOnClickListener(this);
opt_4.setOnClickListener(this);
text_player_second.setVisibility(View.GONE);
vs_word.setVisibility(View.GONE);
player_second_pic.setVisibility(View.GONE);
player_second_box.setVisibility(View.GONE);
red_point1.setVisibility(View.GONE);
text_number_pt1.setVisibility(View.GONE);
text_number1.setVisibility(View.GONE);
countDownTimer = new MyCountDownTimer(startTime, interval);
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
pg_loading.setProgress(progressStatus);
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
splashThread = new Thread() {
public void run() {
try {
sleep(6000);
// Utils.systemUpgrade(SplashActivity.this);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = null;
intent = new Intent(SinglePlayerOption.this,
NoResponseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
};
splashThread.start();
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.option_1:
splashThread.stop();
countDownTimer.onFinish();
Toast.makeText(SinglePlayerOption.this,
timer_text.getText().toString(), 1).show();
i = new Intent(SinglePlayerOption.this,
DialogLeaderboardActivity.class);
startActivity(i);
break;
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timer_text.setText("Time's up!");
}
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("" + millisUntilFinished / 1000);
}
}
}
Thread th = new Thread(new Runnable() {
public void run() { ....
th.start();//starts
th.interrupt();//this stops.
and use
while (progressStatus < 100 && (!Thread.currentThread().isInterrupted())){....
instead of
while (progressStatus < 100) {....
Now i want to stop the progress at the same time when user clicks on
a button.I have tried thread.stop()
Thread.stop() is deprecated and you should not use it. The basic concept to understand is that a thread terminates is execution when the last line of code of his run method is executed. In the case of your "ProgressBar Thread*, when the user press the button, you have to set the exit condition of your while-loop (progressStatus = 100) in order to make it terminate
I am new to Android development and am working on an app that I use for my work. It required multiple buttons to each pay a sound. It is however more complicated than that.
I have managed to make a mediaplayer that will play sounds, pause, fade etc from buttons giving the button tag a string that is passed to the player as file to play. I can press other buttons and start a new sound without problems after stopping and releasing the MP. My problem is As this is for my theatre show. I want to be able to cross mix (i.e as one sound fades the next is starting). The first thought is I need a different MP for each button (which would use a lot of copy code) and also I want to be able to set up nearly 100 buttons.
Has anyone done this before, I have searched for hours online to find very little help. Any help would be useful thank you in advance.
My code is below
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnLongClickListener;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
MediaPlayer mp, mp2 ;
Button Sound1 ,Sound2, Stop, Pause , Fade;
TextView displaystatus;
String bName = "button pressed";
//set variables for volume control
private int iVolume;
private final static int INT_VOLUME_MAX = 100;
private final static int INT_VOLUME_MIN = 0;
private final static float FLOAT_VOLUME_MAX = 1;
private final static float FLOAT_VOLUME_MIN = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//connect interface to local variables
Fade=(Button)findViewById(R.id.bfade);
Sound1 = (Button)findViewById(R.id.bSound1);
Sound2 = (Button)findViewById(R.id.bSound2);
Stop =(Button)findViewById(R.id.bStop); Pause=(Button)findViewById(R.id.bPause);
displaystatus=(TextView)findViewById(R.id.tStatus);
mp2=new MediaPlayer();
//Button clicks to make play/pause/stop
Sound1.setOnClickListener(buttonPlayOnClickListener);
Sound2.setOnClickListener(buttonPlayOnClickListener);
Pause.setOnClickListener(buttonPauseOnClickListener);
Stop.setOnClickListener( buttonQuitOnClickListener);
Fade.setOnClickListener( buttonFadeOnClickListener);
//set onlongclicklistener to open SoundDetailActivity
Sound1.setOnLongClickListener(new View.OnLongClickListener(){
public boolean onLongClick(View v) {
//get the tag for the button pressed
bName= v.getTag().toString();
whenLongClick();
return true;
};
});
//set long click listener to open SoundDetailActivity
Sound2.setOnLongClickListener(new View.OnLongClickListener(){
public boolean onLongClick(View v) {
//get the tag for the button pressed
bName= v.getTag().toString();
whenLongClick();
return true;
};
});
}
private void initMediaPlayer ()
{
if(mp!=null){mp.stop();
mp.release();}
mp = new MediaPlayer();
File path=android.os.Environment.getExternalStorageDirectory();
try {
Log.v("paddy",path+bName);
mp.setDataSource(path+bName );
mp.prepare();
}catch (IOException e){
e.printStackTrace();
}
}
Button.OnClickListener buttonPlayOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
bName= v.getTag().toString();
initMediaPlayer();
Log.v("paddy",bName);
// if(mp.isPlaying()) {mp.reset();}
mp.start();
displaystatus.setText("- PLAYING -");
Pause.setText("Pause");
Log.v("paddy","no sound was playing");
}
};
Button.OnClickListener buttonPauseOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mp.isPlaying()) {
mp.pause();
displaystatus.setText("- resume -");
Pause.setText("Resume");
}else{
mp.start();
displaystatus.setText("- playing -");
Pause.setText("Pause");
}
//finish();
}
};
Button.OnClickListener buttonQuitOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
mp.reset();
displaystatus.setText("- Ready -");
}
};
public Button.OnClickListener buttonFadeOnClickListener
=new Button.OnClickListener(){
#Override
public void onClick(View v) {
fade(5000); ///time in milliseconds
// TODO Auto-generated method stub
// mp.stop();
displaystatus.setText("- Fade out -");
//finish();
}
};
public void fade(int fadeDuration)
{
//Set current volume, depending on fade or not
if (fadeDuration > 0)
iVolume = INT_VOLUME_MAX;
else
iVolume = INT_VOLUME_MIN;
updateVolume(0);
//Start increasing volume in increments
if(fadeDuration > 0)
{
final Timer timer = new Timer(true);
TimerTask timerTask = new TimerTask()
{
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
updateVolume(-1);
if (iVolume <= INT_VOLUME_MIN) {
timer.cancel();
timer.purge();
//Pause music
if (mp.isPlaying()) mp.stop();
mp.release();
mp = new MediaPlayer();
mp = MediaPlayer.create(MainActivity.this, R.raw.franksinatra);
displaystatus.setText("- Ready -");
Log.v("paddy","getting to end of fade");
}
}
});
}
};
// calculate delay, cannot be zero, set to 1 if zero
int delay = fadeDuration/INT_VOLUME_MAX;
if (delay == 0) delay = 1;
timer.schedule(timerTask, delay, delay);
}
}
// when a button is longclicked the activity sound details is opened and the sound button tag is sent as an extra.
public void whenLongClick () {
Toast.makeText(getApplicationContext(), bName , Toast.LENGTH_LONG).show();
Intent i = new Intent(this,SoundDetailActivity.class);
i.putExtra("ButtonId",bName);
startActivity(i);
}
private void updateVolume(int change)
{
//increment or decrement depending on type of fade
iVolume = iVolume + change;
//ensure iVolume within boundaries
if (iVolume < INT_VOLUME_MIN)
iVolume = INT_VOLUME_MIN;
else if (iVolume > INT_VOLUME_MAX)
iVolume = INT_VOLUME_MAX;
//convert to float value
float fVolume = 1 - ((float) Math.log(INT_VOLUME_MAX - iVolume) / (float) Math.log(INT_VOLUME_MAX));
//ensure fVolume within boundaries
if (fVolume < FLOAT_VOLUME_MIN)
fVolume = FLOAT_VOLUME_MIN;
else if (fVolume > FLOAT_VOLUME_MAX)
fVolume = FLOAT_VOLUME_MAX;
mp.setVolume(fVolume, fVolume);
}
}
I've created an app (radio streaming) but doesn't works on S4.
I've tested this app on my Galaxy Nexus, Xperia Arc s, Htc Desire and it works properly.
I think there is an error in my code.
My code:
package com.dieesoft.radiolluvia;
import java.io.IOException;
import android.R.array;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.TrackInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
private ProgressDialog pb;
private Button bplay;
private Button bstop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bplay = (Button) findViewById(R.id.button1);
bstop = (Button) findViewById(R.id.button2);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
bplay.setOnClickListener(this);
bstop.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.button1 )
{
//button play
new iniciarStreaming().execute();
Toast.makeText(this, "Play", Toast.LENGTH_SHORT).show();
}
else if(v.getId() == R.id.button2)
{
//button stop
Toast.makeText(this, "Stop", Toast.LENGTH_SHORT).show();
mp.stop();
}
}
private class iniciarStreaming extends AsyncTask<Void, Void, Boolean> implements OnPreparedListener
{
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
mp.setDataSource("http://makrodigital.com:8134/radiolluvia");
} 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();
}
mp.prepareAsync();
mp.setOnPreparedListener(this);
return null;
}
protected void onPreExecute() {
// TODO Auto-generated method stub
pb = new ProgressDialog(MainActivity.this);
pb.setMessage("Buffering...");
pb.show();
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
if (pb.isShowing()) {
pb.cancel();
}
mp.start();
}
}
Your streaming url (http://makrodigital.com:8134/radiolluvia) has AAC format with content-type: audio/aacp.
But audio/aacp streaming is not supported directly. Maybe previously was another link? MP3 or something else?
For playing this url you can use this library:
http://code.google.com/p/aacplayer-android/
i have a little bit of a problem here when calling a new thread.
I am making a audio recording app and i call the recording/playback in separate threads.
There is a button to start the recording. I am trying to update the button with new text via a handler.post object and method.
The problem is it takes too long to update. The text doesnt update till after the thread(s) run +5 secs longer.
can someone help me? please?
package com.EJH.Industries.microkr;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.media.MediaSyncEvent;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
//CLASS VARIABLES
//CHAR SEQUENCE
CharSequence easyChar = "PLAYING";
public Handler textViewHandler = new Handler();
//CREATE THE RECORDING OBJECT
int audioSrc = MediaRecorder.AudioSource.MIC;
int sampleRate = 44100;
int chanConfig = AudioFormat.CHANNEL_IN_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int getMinBuffSize = 200*AudioRecord.getMinBufferSize(sampleRate, chanConfig, audioFormat);
int minBuffSize = (int) getMinBuffSize;
short audioBuff[] = new short[minBuffSize];
public AudioRecord micRecorder = new AudioRecord(audioSrc, 22050, chanConfig, audioFormat, minBuffSize);
//CREATE THE PLAYBACK OBJECT
int streamType = AudioManager.STREAM_MUSIC;
int playMode = AudioTrack.MODE_STREAM;
int playChanConfig = AudioFormat. CHANNEL_OUT_MONO;
public AudioTrack speakerPlay = new AudioTrack(streamType, sampleRate, playChanConfig, audioFormat, 8192, playMode);
public void startRec(){
micRecorder.startRecording();
micRecorder.read(audioBuff, 0, minBuffSize);
micRecorder.stop();
micRecorder.release();
}
public void startPlayback(){
speakerPlay.play();
speakerPlay.write(audioBuff, 0, minBuffSize);
speakerPlay.stop();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button startBtn = (Button) findViewById(R.id.startButton);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Thread recThread = new Thread( new Runnable(){
public void run() {
// TODO Auto-generated method stub
textViewHandler.post(new Runnable () {
public void run(){
startBtn.setText("Recording!");
}
});
startRec();
}
});
// RUN RECORDING FUNCTION
recThread.run();
try {
recThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread playThread = new Thread( new Runnable(){
public void run() {
// TODO Auto-generated method stub
startPlayback();
}
});
playThread.run();
try {
playThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
///////END onCreate//////////
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I think so it is because you are calling startRec() first and then running the recThread..try to modify your code as below..that is remove your startRec() function from above recThread.run() line and add it after try catch..hope it helped you..
Thread recThread = new Thread( new Runnable(){
public void run() {
// TODO Auto-generated method stub
textViewHandler.post(new Runnable () {
public void run(){
startBtn.setText("Recording!");
}
});
//remove it from here..
// startRec();
}
});
// RUN RECORDING FUNCTION
recThread.run();
try {
recThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//add here..
startRec();