我有一个Android应用程序,它正在录制音频,并将名称audiorecorder输出到手机上的本地存储。 现在我想将.txt文件存储在同一目录中。
我已尝试过堆栈溢出的几种方法,应用程序没有抱怨,但没有按原样存储.txt。我无法弄清楚原因。
感兴趣的方法是:CreateTxt和generateNote。这些是没有做到的。
这些方法在startR.setOnClickListener方法中使用。
有人能看出原因吗?提前谢谢。
package xxxx;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class DataCollectionActivity extends AppCompatActivity {
private MediaPlayer mediaPLayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
public Button GoToUserAcc;
public Button GoToLogin;
public Button GoToTest;
// Permission Variables
private static final String LOG_TAG = "AudioRecordTest";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private static String mFileName = null;
private boolean permissionToRecordAccepted = false;
private String [] permissions =
{Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET};
private static final int
REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 200;
private boolean permissionToWriteExternalStoragedAccepted =
false;
private static final int REQUEST_INTERNET_PERMISSION = 200;
private boolean permissionToUseInternetAccepted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_collec);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
Button startR = (Button) findViewById(R.id.Bstart);
Button stopR = (Button) findViewById(R.id.Bstop);
Button playRecording = (Button) findViewById(R.id.playBtn);
Button stopPlaying = (Button) findViewById(R.id.stopBtn);
final TextView statusTV;
statusTV = (TextView) findViewById(R.id.tStatus);
OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
ActivityCompat.requestPermissions(this, permissions,
REQUEST_RECORD_AUDIO_PERMISSION);
/*------START recording BUTTON------*/
startR.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
beginRecording();
stv.setText("Recording");
//CreateTxt();
generateNote("MLdata", "sBody");
stv.setText("Created txt");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
stv.setText("Error");
}
}
});
/*------STOP BUTTON------*/
stopR.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
stopRecording();
stv.setText("Stopped");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
Log.d("here","dd",e);
}
}
});
}
private void stopPlayback() throws Exception{
if(mediaPLayer != null)
mediaPLayer.stop();
}
private void playRecording() throws IOException {
ditchMediaPLayer();
mediaPLayer = new MediaPlayer();
mediaPLayer.setDataSource(OUTPUT_FILE);
mediaPLayer.prepare();
mediaPLayer.start();
}
private void ditchMediaPLayer() {
if (mediaPLayer != null) {
try{
mediaPLayer.release();
} catch(Exception e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
if(recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception{
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
//DataCollectionActivity dca = new DataCollectionActivity();
//dca.CreateTxt();
if (outFile.exists()) {
outFile.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.
OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
/*API constraints
Container WAV
Encoding PCM
Rate 16K
Sample Format 16 bit OK
Channels Mono OK
*/
recorder.setAudioSamplingRate(16);
//channel 1 equals mono, 2 eqals stereo
recorder.setAudioChannels(1);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
if(recorder != null)
recorder.release();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == R.id.action_setting){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on setting action menu", Toast.LENGTH_SHORT).show();
}
if (item.getItemId() == R.id.action_about_us){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on about us action menu", Toast.LENGTH_SHORT).show();
goToUserAccount();
}
return super.onOptionsItemSelected(item);
}
// Requesting permission to RECORD_AUDIO
//fra android.com
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION:
permissionToWriteExternalStoragedAccepted =
grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_INTERNET_PERMISSION:
permissionToUseInternetAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mMenuInflater = getMenuInflater();
mMenuInflater.inflate(R.menu.menu_main, menu);
return true;
}
/** Opens up new activity */
//Vedrører tollbaren som ligenu ikke bliver brugt /virker ikke.
public void goToUserAccount() {
Intent intent = new Intent(this, UserAccountActivity.class);
EditText editText = (EditText)
findViewById(R.id.action_about_us);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
//Metode som laver en writer.
public void CreateTxt() throws IOException {
//concerning txt file
int id = 0;
String typeId = "S";
EditText db = (EditText) findViewById(R.id.dbNoiseText);
String dbString = db.getText().toString();
EditText numPar = (EditText)
findViewById(R.id.participatorsText);
String npar = numPar.getText().toString();
EditText conversationBool = (EditText)
findViewById(R.id.CoverationText);
String cBool = conversationBool.getText().toString();
File f = new File(Environment.getExternalStorageDirectory().
getAbsolutePath()+"dataForML.txt");
try {
System.out.print("enters try in createtxt");
PrintWriter writer = new PrintWriter(f, "UTF-8");
writer.println(dbString + ", ");
writer.println(npar + ", ");
writer.println(cBool + ", ");
writer.println(typeId + id + ", ");
writer.println(Environment.getExternalStorageDirectory().
getAbsolutePath()+"/dataForML.txt");
//Her skal den skrive binary. Metoden ligger i asrRequest
writer.println("Path to Acceleroeter CSV file ");
writer.println("\n");
writer.println();
writer.close();
id++;
} catch (IOException e) {
e.printStackTrace();
}
}
//OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
//generateNoteOnSD("MLdata", "sBody");
public void generateNote(String sFileName, String sBody) {
try {
File root = new
File(Environment.getExternalStorageDirectory().
getAbsolutePath(), "NotesML");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
//Toast.makeText(context, "Saved",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void thirdTry(){
String FILENAME = "hello_file";
String string = "hello world!";
try{
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
layout xml comes here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:id="@+id/dbNoiseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="db noise"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="@+id/participatorsText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="# participators"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="@+id/CoverationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Conversation? Y/N"
android:inputType="textPersonName"
android:textAlignment="center" />
<Button
android:id="@+id/Bstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Start Recording" />
<Button
android:id="@+id/Bstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Stop recording" />
<TextView
android:id="@+id/tStatus"
android:layout_width="354dp"
android:layout_height="42dp"
android:text="status"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
Manifest comes here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dk.itu.percomp17.jumanji">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".UserAccountActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity"/>
<activity android:name=".DataCollectionActivity"/>
<activity android:name=".CallingjsActivity">
</activity>
</application>
</manifest>
答案 0 :(得分:0)
我发现了。以下方法解决了它。
// Once a file has been created, use this method to publicize
//the file as it can be seen !!
// But be sure to add "Context context;" outside of the method.
// Plus, remember to add "context = getApplicationContext ();" in the
//onCreate () method.
public void scanFile(String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}