gpt4 book ai didi

android - 如何在android中录制音频并上传到服务器?如何使用文档附件限制特定的文件扩展名?

转载 作者:行者123 更新时间:2023-11-29 19:08:28 24 4
gpt4 key购买 nike

我正在使用与 whatsapp 相同的 android 附件。我可以通过相机拍照、图库选项、位置、录制视频。我坚持使用两个选项,

  1. 如何录制音频?

点击音频按钮时,我使用了以下代码,

        audioIB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, 6);

}
});

并且正在重定向到录制音频但在文件保存后它没有重定向到 Activity 。onActivityResult 中的代码是什么。

  1. 我如何在附加文件时限制特定的文件扩展名,我需要选择 doc、txt、pdf、音频文件。其余的我不想附加。我尝试了很多但我做不到.Please help me asp.This is my code after you mentioned link using,以下代码我一直在使用,

    private void showFileChooser() 
    {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    // intent.setType("application/*");

    intent.setType("application/pdf|application/doc|appl‌​ication/docm|applica‌​tion/docx|applicatio‌​n/dot|application/mc‌​w|application/rtf" + "|application/pages|application/odt|application/ott");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try
    {
    startActivityForResult(
    Intent.createChooser(intent, "Select a File to Upload"),
    4);
    }
    catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(getActivity(), "Please install a File Manager.",
    Toast.LENGTH_SHORT).show();
    }
    }

最佳答案

对于音频录制,通常正常的 Intent MediaStore.Audio.Media.RECORD_SOUND_ACTION 将用于录制音频并将路径返回到 onActivityResult() 中的 Activity 方法。

为此,这是示例代码。

 int RQS_RECORDING = 1;
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, RQS_RECORDING);

在您的 OnActivityResult() 中,您的代码将是这样的,

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RQS_RECORDING){

if(resultCode == Activity.RESULT_OK){

// Great! User has recorded and saved the audio file

if(data!=null)
{
String savedUri = data.getData();

Log.d("debug" , "Record Path:" + savedUri);

Toast.makeText(MainActivity.this,
"Saved: " + result,
Toast.LENGTH_LONG).show();
}

}
if (resultCode == Activity.RESULT_CANCELED) {
// Oops! User has canceled the recording
}
}
}

但是不,它不适用于所有情况,并且某些设备(离体 V3 等)记录已保存,但不会返回任何数据,即(数据为空)和某些设备一些其他选项也在录音中(如删除、重试、播放、暂停等),我们可能也不需要。

因此,除了默认 Intent 之外,您还可以使用 MediaRecorder 创建自定义 Recording,如下所示。

示例代码。

AudioRecordActivity.Class

 public class AudioRecordActivity extends AppCompatActivity {

Button buttonStart, buttonStop ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_record_activity);

buttonStart = (Button) findViewById(R.id.button);
buttonStop = (Button) findViewById(R.id.button2);
buttonStop.setEnabled(false);

random = new Random();

buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if(checkPermission()) {

AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";

MediaRecorderReady();

try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

buttonStart.setEnabled(false);
buttonStop.setEnabled(true);

Toast.makeText(AudioRecordActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}

}
});

buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);

Toast.makeText(AudioRecordActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();

Intent returnIntent = new Intent();
returnIntent.putExtra("result",AudioSavePathInDevice);
setResult(Activity.RESULT_OK,returnIntent);
finish();

}
});

}

public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}

public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));

i++ ;
}
return stringBuilder.toString();
}

private void requestPermission() {
ActivityCompat.requestPermissions(AudioRecordActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;

if (StoragePermission && RecordPermission) {
Toast.makeText(AudioRecordActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AudioRecordActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}

public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}

audio_record_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="40dp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="40dp">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@mipmap/ic_launcher_round"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
/>

</RelativeLayout>

AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.STORAGE" />

因此,无论您想在哪里录制音频/声音,您都可以简单地使用下面的代码,并在结果 Activity 中返回您保存的路径。

int RQS_RECORDING = 1;
Intent intent = new Intent(MainActivity.this , AudioRecordActivity.class);
startActivityForResult(intent, RQS_RECORDING);

OnActivityResult() 会是这样

  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == RQS_RECORDING){

if(resultCode == Activity.RESULT_OK){

// Great! User has recorded and saved the audio file
String result=data.getStringExtra("result");

Toast.makeText(MainActivity.this,
"Saved: " + result,
Toast.LENGTH_LONG).show();

Log.d("debug" , "Saved Path::" + result);


}
if (resultCode == Activity.RESULT_CANCELED) {
// Oops! User has canceled the recording / back button
}

}

}

这是一个示例代码,您可以根据自己的需要自定义您的要求。

This是一个提供记录控制的库

对于第二个问题,我已经给出了 link ,你可以像下面这样使用。

private void browseDocuments(){

String[] mimeTypes =
{"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip"};

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent,"ChooseFile"), REQUEST_CODE_DOC);

}

关于android - 如何在android中录制音频并上传到服务器?如何使用文档附件限制特定的文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46275676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com