#android #audio #android-recyclerview #media-player #record
#Android #Аудио #android-recyclerview #медиаплеер #запись
Вопрос:
Запись и остановка работают нормально, но когда я пытаюсь воспроизвести, это вызывает ошибку. Я пробовал запустить метод воспроизведения в фоновом потоке и пробовал его с помощью и без передачи имени файла через метод воспроизведения, но безуспешно. Также, когда я устанавливаю точку останова в своем методе воспроизведения, он пропускает mPlayer.start(). Я использую recyclerview для хранения своих аудиофайлов.
import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import static android.Manifest.permission.RECORD_AUDIO; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class MainActivity extends AppCompatActivity { private static final int STORAGE_PERMISSION_CODE = 279; public static final int AUDIO_PERMISSION_CODE = 555; private String fileName; private MediaRecorder mRecorder; private MediaPlayer mPlayer; Button recordBtn, stopBtn; private TextView tv; private ArrayListlt;Recordgt; recordingList; private RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recordBtn = (Button) findViewById(R.id.playB); stopBtn = (Button) findViewById(R.id.stopB); tv = (TextView) findViewById(R.id.tv); checkPermission(WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE); checkPermission(READ_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE); checkPermission(RECORD_AUDIO,AUDIO_PERMISSION_CODE); mRecorder = new MediaRecorder(); recordingList = new ArrayListlt;gt;(); recyclerView = findViewById(R.id.rv); setRecordinfo(fileName); setAdapter(); } private void setRecordinfo(String fileName){ recordingList.add(new Record(fileName)); } private void setAdapter() { RecyclerAdapter adapter = new RecyclerAdapter(recordingList); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); } public void onRecordClick(View v) { record(); } public void onStopClick(View v) { stop(); } public void onPlayClick(View v) { play(fileName); } public void play(String fileName){ mPlayer = new MediaPlayer(); tv.setText("Recording Playing"); try { mPlayer.setDataSource(fileName); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { Log.e("TAG", "play failed"); } } public void stop(){ if (mRecorder != null) { mRecorder.stop(); mRecorder.reset(); mRecorder.release(); mRecorder = null; tv.setText("Recording stopped"); } if (mPlayer != null) { mPlayer.stop(); mPlayer.release(); mPlayer = null; tv.setText("Player Stopped"); } } public void record(){ // we are initializing our filename variable // with the path of the recorded audio file. Date createdTime = new Date(); fileName = getExternalCacheDir().getAbsolutePath(); fileName = "/" createdTime "test.mp4" ; mRecorder.reset(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mRecorder.setOutputFile(fileName); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mRecorder.prepare(); mRecorder.start(); tv.setText("Recording"); //mRecorder.stop(); } catch (IOException e) { e.printStackTrace(); Log.d("Audio","unable to prepare"); } } // Function to check and request permission. public void checkPermission(String permission, int requestCode) { if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { Toast.makeText(MainActivity.this, "Storage Permission Granted", Toast.LENGTH_SHORT).show(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.length gt; 0 amp;amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "Storage Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Storage Permission Denied", Toast.LENGTH_SHORT).show(); } if (requestCode == AUDIO_PERMISSION_CODE) { if (grantResults.length gt; 0 amp;amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "audio Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, " Permission Denied", Toast.LENGTH_SHORT).show(); } } } }}
\
import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; //The adapter is the piece that will connect our data to our RecyclerView and determine the ViewHolder(s) which will need to be used to display that data. public class RecyclerAdapter extends RecyclerView.Adapterlt;RecyclerAdapter.MyViewHoldergt; { private ArrayListlt;Recordgt; recordingList; public RecyclerAdapter(ArrayListlt;Recordgt; recordingList){ this.recordingList = recordingList; } public class MyViewHolder extends RecyclerView.ViewHolder{ private TextView recordText; public MyViewHolder(@NonNull View view){ super(view); recordText = view.findViewById(R.id.r2); } } //creates a new RecyclerView.ViewHolder and initializes some private fields to be used by RecyclerView. // allows us to use the resource id with the LayoutInflater in the onCreateViewHolder() method and then return the ViewHolder. @NonNull @Override public RecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recordings,parent,false); return new MyViewHolder(itemView); } //displays data at a specific index using recycled views //This method is called for each ViewHolder to bind it to the adapter. This is where we will pass our data to our ViewHolder. @Override public void onBindViewHolder(@NonNull RecyclerAdapter.MyViewHolder holder, int position) { String record = recordingList.get(position).getRecordings(); holder.recordText.setText(record); } //returns size of arraylist //This method returns the size of the collection that contains the items we want to display. @Override public int getItemCount() { return recordingList.size(); } }
\
import android.content.Context; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Record { private String recording; public Record(String recording) { this.recording = recording; } public String getRecordings() { return recording; } public void setRecordings(String recordings) { this.recording = recording; } }
Комментарии:
1. Я все понял! Медиаплееру не удалось найти файл. Я отредактировал путь к файлу, и теперь он работает!