我正在开发一个记录音频的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)
)应用程序卡住了。关于这个问题的任何帮助将不胜感激
答案 0 :(得分:1)
最后我的自我发现答案包括在另一个帖子中保存文件选项:
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();
}
答案 1 :(得分:0)
你确定
f = new File("ext_card/ex.pcm");
实际上可以创建文件吗?
有一个正确的方法Environment.getExternalStorageDirectory()
要执行此操作,这需要设置清单中的权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
此外,如果您希望录制服务从MainUI线程中分离出来,您可以使用IntentService代替。