可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have tried simplifying the code to the bare minimum and it still doesn't work:
public class MainActivity extends AppCompatActivity { AudioRecord rec; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rec= new AudioRecord(MediaRecorder.AudioSource.MIC,44100, AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,8192); short buff[] = new short[8192]; int read = rec.read(buff,0,buff.length); System.out.print(read); }
Always returns -3 no matter what. What am I missing?
回答1:
Together with my friend we have finally managed to solve this issue. You need to call AudioRecord.startRecording() before calling read(). Also after you're done you should call AudioRecord.stop(). I wonder why it's so hard to find this basic piece of information
回答2:
Did you checked the permissions in manifest ?
</application> <uses-permission android:name="android.permission.RECORD_AUDIO" />
Documentation says :
Reads audio data from the audio hardware for recording into a byte array. The format specified in the AudioRecord constructor should be ENCODING_PCM_8BIT to correspond to the data in the array.
Parameters
audioData byte: the array to which the recorded audio data is written. This value must never be null.
offsetInBytes int: index in audioData from which the data is written expressed in bytes.
sizeInBytes int: the number of requested bytes. Returns
int zero or the positive number of bytes that were read, or one of the following error codes. The number of bytes will not exceed sizeInBytes.
ERROR_INVALID_OPERATION if the object isn't properly initialized
i think you should check the initialization of AudioRecord object. So look at this answer : Android AudioRecord example
回答3:
According to the Android documentation -
-3 indicates that it is an invalid operation.
Denotes a failure due to the improper use of a method.
Constant Value: -3 (0xfffffffd)
This problem is mostly likely because it couldn't create an AudioRecord
instance with the parameters that you have specified.
After you create the object try to check whether it was initialized correctly via the method getState
if (rec.getState() == AudioRecord.STATE_UNINITIALIZED) { // Oops looks like it was not initalized correctly }
If it is the state is indeed uninitialized then try setting different audio properties. Check the documentation for AudioRecord
[constructor](https://developer.android.com/reference/android/media/AudioRecord.html#AudioRecord(int, int, int, int, int)), the documentation provides a comprehensive details on how to initialize the different parameters.