我在我的应用中使用this库来录制音频。
这是我的代码:
String filePath;
recordAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(getBaseContext(),
android.Manifest.permission.RECORD_AUDIO) + ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_LOCATION);
}
if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.RECORD_AUDIO) +
ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
filePath = Environment.getExternalStorageDirectory() + "/recorded_audio.wav";
int color = getResources().getColor(R.color.colorPrimaryDark);
AndroidAudioRecorder.with(MainActivity.this)
// Required
.setFilePath(filePath)
.setColor(color)
.setRequestCode(RECORD_PRODUCT_DAMAGE)
// Optional
.setSource(AudioSource.MIC)
.setChannel(AudioChannel.STEREO)
.setSampleRate(AudioSampleRate.HZ_48000)
.setAutoStart(true)
.setKeepDisplayOn(true)
// Start recording
.record();
}
}
});
以下是onActivityResult()
中的代码:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_PRODUCT_DAMAGE) {
if (resultCode == RESULT_OK) {
// Great! User has recorded and saved the audio file
Toast.makeText(this, "Audio recorded successfully!", Toast.LENGTH_SHORT).show();
if (data == null) {
Toast.makeText(this, "Data is null", Toast.LENGTH_SHORT).show();
}
playRecordedAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uriPath = null;
uriPath = Uri.fromFile(new File(filePath));
try{
mp = MediaPlayer.create(getBaseContext(), uriPath);
mp.start();
}catch(NullPointerException e) {
// handle NullPointerException
}
}
});
} else if (resultCode == RESULT_CANCELED) {
// Oops! User has canceled the recording
Toast.makeText(this, "Audio was not recorded", Toast.LENGTH_SHORT).show();
}
}
}
此处显示Toast
'数据为空'。
为什么会这样?为什么我无法将录制的音频文件作为data
来获取?
请告诉我。