AudioRecord 개체가 초기화되지 않음
아래 코드에서 내 audioRecord
개체가 초기화되지 않습니다. 나는 그것을 onCreate
방법으로 옮기고 그것을 글로벌로 만들었습니다. 상태를 기록했고 1
사용할 준비가되었음을 의미 하는 값을 반환합니다 . 디버거는 startRecording
초기화되지 않은 개체에서 호출되고 있다고 말합니다 . 음원을 얻을 수 없다는 말도있다.
이러한 오류가 발생하는 이유는 무엇입니까?
package com.tecmark;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class recorder extends Activity {
private Thread thread;
private boolean isRecording;
private AudioRecord recorder;
private FileOutputStream os;
private BufferedOutputStream bos;
private DataOutputStream dos;
private TextView text;
private int audioSource = MediaRecorder.AudioSource.MIC;
private int sampleRate = 22050;
private int channel = AudioFormat.CHANNEL_CONFIGURATION_MONO;
private int encoding = AudioFormat.ENCODING_PCM_16BIT;
private int result = 0;
private int bufferSize;
private byte[] buffer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.v("onCreate", "layout set, about to init audiorec obj");
text = (TextView)findViewById(R.id.TextView01);
bufferSize = AudioRecord.getMinBufferSize(sampleRate,channel,encoding);
buffer = new byte[bufferSize];
recorder = new AudioRecord(audioSource, sampleRate,channel,encoding,
AudioRecord.getMinBufferSize(sampleRate, channel,encoding));
Log.i("recorder obj state",""+recorder.getRecordingState());
}
public void onClickPlay(View v){
}
public void record(){
Log.i("inside record method", "******");
File path = Environment.getExternalStorageDirectory();
Log.v("file path", ""+path.getAbsolutePath());
File file = new File(path, "test.wav");
if(file.exists()){
file.delete();
}
path.mkdirs();
Log.v("file path", ""+file.getAbsolutePath());
try {
os = new FileOutputStream(file);
bos = new BufferedOutputStream(os);
dos = new DataOutputStream(bos);
} catch (Exception e1) {
e1.printStackTrace();
}
int bufferSize = AudioRecord.getMinBufferSize(sampleRate,channel,encoding);
byte[] buffer = new byte[bufferSize];
recorder.startRecording();
isRecording = true;
try{
while (isRecording){
result = recorder.read(buffer, 0, bufferSize);
for(int a=0; a<result;a++){
dos.write(buffer[a]);
if(!isRecording){
recorder.stop();
break;
}
}
}
dos.flush();
dos.close();
}catch(Exception e){
e.printStackTrace();
}
}// end of record method
public void onClickStop(View v){
Log.v("onClickStop", "stop clicked");
isRecording=false;
}
public void onClickReverse(View v){
Log.v("onClickReverse", "reverse clicked");
}
public void onClickRecord(View v){
Log.v("onClickRecourd", "record clicked, thread gona start");
text.setText("recording");
thread = new Thread(new Runnable() {
public void run() {
isRecording = true;
record();
}
});
thread.start();
isRecording = false;
}
}//end of class
Logcat
01-30 15:23:16.724: ERROR/AudioRecord(12817): Could not get audio input for record source 1 01-30 15:23:16.729:
ERROR/AudioRecord-JNI(12817): Error creating AudioRecord instance: initialization check failed. 01-30 15:23:16.729:
ERROR/AudioRecord-Java(12817): [ android.media.AudioRecord ] Error code
-20 when initializing native AudioRecord object. 01-30 15:23:16.729: INFO/recorder obj state(12817): 1 01-30 15:23:16.729:
WARN/dalvikvm(12817): threadid=13: thread exiting with uncaught exception (group=0x4001b180) 01-30 15:23:16.729:
ERROR/AndroidRuntime(12817): Uncaught handler: thread Thread-7 exiting due to uncaught exception 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord. 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at android.media.AudioRecord.startRecording(AudioRecord.java:495) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at com.tecmark.recorder.record(recorder.java:114) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at com.tecmark.recorder$1.run(recorder.java:175) 01-30 15:23:16.739:
ERROR/AndroidRuntime(12817): at java.lang.Thread.run(Thread.java:1096)
AudioRecord를 사용할 때의 비결은 각 장치가 다른 초기화 설정을 가질 수 있으므로 비트 전송률, 인코딩 등의 가능한 모든 조합을 반복하는 메서드를 만들어야한다는 것입니다.
private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
public AudioRecord findAudioRecord() {
for (int rate : mSampleRates) {
for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
try {
Log.d(C.TAG, "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
+ channelConfig);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
// check if we can instantiate and have a success
AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
return recorder;
}
} catch (Exception e) {
Log.e(C.TAG, rate + "Exception, keep trying.",e);
}
}
}
}
return null;
}
AudioRecord recorder = findAudioRecord();
recorder.release();
나는 같은 문제가 있었는데
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
매니페스트에.
Lollipop 이후로 사용자에게 각 권한을 구체적으로 요청해야합니다. 해지했을 수 있습니다. 권한이 부여되었는지 확인하십시오.
According to the javadocs, all devices are guaranteed to support this format (for recording):
44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT.
Change to CHANNEL_OUT_MONO for playback.
Now, with lollipop, you need to specifically ask the user for each permission. Make sure the permission is granted.
Even after doing all of the above steps I was getting the same issue, what worked for me was that my os was marshmallow and I had to ask for permissions.
Problem with initializing few AudioRecord objects could by fixed by using audioRecord.release();
before creating next object... More here: Android AudioRecord - Won't Initialize 2nd time
Just had the same problem. The solution was to restart the device. While playing with the code I did not release the AudioRecord Object which obviously caused the audio device to stuck. To test whether the audio device worked or not I downloaded Audalyzer from Google Play.
If your mobile phone system is Android M or above,perhaps you need to apply record audio permission in Android M.http://developer.android.com/guide/topics/security/permissions.html
in my case I had to manually allow the permission in android 7 for microphone, as sean zhu commented.
I noticed that when the SDCard on the avd I am running gets full the AudioRecord constructor returns null. Have you tried clearing the SDCard?
I think this has to do with the thread not knowing that you've paused the main activity and still trying to record after you've stopped the recorder.
I solved it by changing my onResume() and onPause() methods to modify the isRecording boolean.
public void onResume() {
...
isRecording = true;
}
public void onPause() {
...
isRecording = false;
}
Then in your thread, surround both your startRecording()
and stop()
with if-statements checking for isRecording:
if(isRecording)
recorder.startRecording();
...
if(isRecording)
recorder.stop(); // which you've done
I rewrote the answer from @DustinB for anyone who is using Xamarin Android AudioRecord with C#.
int[] sampleRates = new int[] { 44100, 22050, 11025, 8000 };
Encoding[] encodings = new Encoding[] { Encoding.Pcm8bit, Encoding.Pcm16bit };
ChannelIn[] channelConfigs = new ChannelIn[]{ ChannelIn.Mono, ChannelIn.Stereo };
//Not all of the formats are supported on each device
foreach (int sampleRate in sampleRates)
{
foreach (Encoding encoding in encodings)
{
foreach (ChannelIn channelConfig in channelConfigs)
{
try
{
Console.WriteLine("Attempting rate " + sampleRate + "Hz, bits: " + encoding + ", channel: " + channelConfig);
int bufferSize = AudioRecord.GetMinBufferSize(sampleRate, channelConfig, encoding);
if (bufferSize > 0)
{
// check if we can instantiate and have a success
AudioRecord recorder = new AudioRecord(AudioSource.Mic, sampleRate, channelConfig, encoding, bufferSize);
if (recorder.State == State.Initialized)
{
mBufferSize = bufferSize;
mSampleRate = sampleRate;
mChannelConfig = channelConfig;
mEncoding = encoding;
recorder.Release();
recorder = null;
return true;
}
}
}
catch (Exception ex)
{
Console.WriteLine(sampleRate + "Exception, keep trying." + ex.Message);
}
}
}
}
참고URL : https://stackoverflow.com/questions/4843739/audiorecord-object-not-initializing
'developer tip' 카테고리의 다른 글
IntelliJ IDEA 렌더링 오류 (0) | 2020.11.29 |
---|---|
Android 팝업 창 닫기 (0) | 2020.11.29 |
S3 및 AWS 콘솔을 사용하여 하위 폴더가있는 폴더 업로드 (0) | 2020.11.29 |
YouTube : 음소거 된 동영상 임베드 방법 (0) | 2020.11.29 |
파일 내에서 문자열의 발생을 어떻게 계산할 수 있습니까? (0) | 2020.11.29 |