我正在开发一个录制音频的 Android 应用程序.. 这是我的 MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v){
Intent intent = new Intent(this,RecordService.class);
startService(intent);
}
public void stop(View v){
Intent intent = new Intent(this,RecordService.class);
stopService(intent);
}
}
服务是
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Service;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
public class RecordService extends Service {
AudioRecord ar;
boolean isRecording = false;
final int SAMPLE_RATE = 44100;
int bufferSize;
byte[] b;
File f;
OutputStream os;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
f = new File("ext_card/ex.pcm");
startRecord();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
stopRecording();
super.onDestroy();
}
private void startRecord(){
bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
ar = new AudioRecord(AudioSource.DEFAULT, SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_DEFAULT,AudioFormat.ENCODING_PCM_16BIT, bufferSize);
isRecording = true;
b = new byte[bufferSize];
try {
os = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(isRecording){
ar.read(b, 0, bufferSize);
try {
os.write(b);
Log.i("File", "Writing file");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
if(isRecording){
ar.stop();
ar.release();
}
}
}
但我的问题是当单击“开始”按钮时(“开始”按钮调用 start(View v)
)应用程序卡住了。任何有关此问题的帮助将不胜感激
最佳答案
最后我自己找到了答案,包括在不同线程中保存文件选项:
private void startRecord(){
bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
ar = new AudioRecord(AudioSource.DEFAULT, SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_DEFAULT,AudioFormat.ENCODING_PCM_16BIT, bufferSize);
isRecording = true;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
writeAudioDataToFile();
}
});
t.start();
}
关于使用音频记录 api 的 Android 录音应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20788660/