我正在我的应用程序中录制音频,我正在努力使用MediaRecorder课程
import android.media.MediaRecorder;
问题是代码编译但似乎没有在API级别<26的设备上运行,因为根据Android Studio中的内联错误消息,显然API 26之前的函数MediaRecorder.setOutputFormat()
不存在。类似地,当我在带有API 24的模拟器上运行代码时,我遇到了运行时错误:
java.lang.NoSuchMethodError: No virtual method setOutputFile(Ljava/io/File;)V in class Landroid/media/MediaRecorder; or its super classes (declaration of 'android.media.MediaRecorder' appears in /system/framework/framework.jar)
作为一个快速修复,我只是将gradle文件中的最小SDK级别增加到26并且everthing工作正常。但是,我不希望我的应用程序被限制在Android 8.0及更高版本,因为7.x仍然如此受欢迎。
所以我的第一个问题是:怎么可能只有整个MediaRecorder
库的一个功能不可用,人们如何在API 26之前使用MediaRecorder
?我无法在网上找到任何相关信息。
第二个问题:如何解决问题,以便我可以为API级别24+录制音频?我必须使用另一个图书馆吗?
这是我的活动的一部分,我正在设置录音机并开始录音。再次,当最小的SDK是26时,这很好用...
private MediaRecorder recorder;
private void startRecording(){
if(!recordingActive) {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setAudioChannels(1);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
switch(activeAudioButton) {
case AUDIO_BUTTON_A:
recorder.setOutputFile(tempSoundFileA); // <--
break;
case AUDIO_BUTTON_B:
recorder.setOutputFile(tempSoundFileB); // <--
break;
}
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
recordingActive = true;
runOnUiThread(new Runnable() {
@Override
public void run() {
speakNowTextView.setVisibility(View.VISIBLE);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是我的gradle文件:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.my.app"
minSdkVersion 24
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:preference-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
使用低于26的API级别时,您可以传入包含文件路径的字符串。如果您特别需要使用File对象,请使用Java中的file.getAbsolutePath()
或Kotlin中的file.absolutePath
。
setOutputFile的工作原理是将String作为参数而不是文件。