I want to make application that gives me the list of audio files available in my SDCard and then i should be able to play that audio file from my application. And even pause resume audio playback etc. and function..
Any help on that?
You can see the below code for streaming audio from URL
private void playVideo() {
try {
final String path = "http://www.a1freesoundeffects.com/animals12557/catmeow.wav";
// If the path has not changed, just start the media player
if (path.equals(current) && mp != null) {
mp.start();
return;
}
current = path;
// Create a new media player and set the listeners
mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
if (mp != null) {
mp.stop();
mp.release();
}
}
}
You can try this way.
class Mp3Filter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3"));
}
}
public class AudioPlayer extends ListActivity implements OnClickListener{
private static final String MEDIA_PATH = new String("/sdcard/backup/songs");
private List<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
private int currentPosition = 0;
private static final String TAG = "Audio Player Demo ";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
Button playerButton;
public void onClick(View v) {
if (v.getId() == R.id.play) {
playPause();
}
}
#Override
public void onCreate(Bundle icicle) {
try {
super.onCreate(icicle);
setContentView(R.layout.songlist);
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop_label);
playerButton.setOnClickListener(this);
updateSongList();
//demoPlay();
} catch (NullPointerException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
public void updateSongList() {
File home = new File(MEDIA_PATH);
if (home.listFiles( new Mp3Filter()).length > 0) {
for (File file : home.listFiles( new Mp3Filter())) {
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_item,songs);
setListAdapter(songList);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
currentPosition = position;
playSong(MEDIA_PATH + songs.get(position));
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
// Setup listener so next song starts automatically
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
nextSong();}
});
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
private void nextSong() {
if (++currentPosition >= songs.size()) {
// Last song, just reset currentPosition
currentPosition = 0;
// playSong(MEDIA_PATH + songs.get(currentPosition));
} else {
// Play next song
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
private void demoPause(){
mp.pause();
playerButton.setText(R.string.play_label);
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, notPlaying);
}
// Initiate playing the media player
private void demoPlay(){
mp.start();
playerButton.setText(R.string.stop_label);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, isPlaying);
}
// Toggle between the play and pause
private void playPause() {
if(mp.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
}
Related
I am having 3 tones. I am calling playmusic() function to play 2 of these tones on imageview toggle. when i click on imageview for first time tone1 starts playing. when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
my requiremet is , when i click on imageview for -
(1st time - tone1 should start playing).
(2nd time - tone1 should stop playing and tone2 should start playing)
(3rd time - tone2 should stop playing and tone1 should start playing again)
and so on....
String file=null;
int x=0;
public void playMusic(int i) {
x=i;
if(i==1){
file = R.raw.tone1;
}else if(i==2){
file = R.raw.tone2;
}else{
file = R.raw.tone3;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
Main2Activity.this.getResources().openRawResourceFd(file);
if(assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
I did a small modification on your logic and added mediaplayer.reset(). Here is the solution link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView player = findViewById(R.id.play);
player.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
playMusic(1);
}
});
mediaPlayer = new MediaPlayer();
}
int file = 0;
MediaPlayer mediaPlayer;
int x = 0;
public void playMusic(int i) {
x = x + i;
if (x == 1) {
file = R.raw.tone1;
}
else if (x == 2) {
file = R.raw.tone2;
} else {
x = 0;
file = R.raw.tone3;
}
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
MainActivity.this.getResources().openRawResourceFd(file);
if (assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
}
when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
If that's the only issue, try putting the following line before you call mediaPlayer = new MediaPlayer();:
if (mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
I am developing an application where I want to start recording voice on button click, and also want to start playing video in video view at the same time.
now the app works on android 4.2 and android 5.1 but does not work on the latest device like android 7.0.
Here is the code
public class MainActivity extends Activity
{
Button start,stop,play;
Boolean recording=false;
String press_value="exit";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
boolean let_start_recording=true;
ImageView startIV,profileIV;
boolean recording_is_in_progress=false;
VideoView vv ;
MediaPlayer mPlayer;
RelativeLayout mainRel;
///new media player
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startIV=(ImageView)findViewById(R.id.imageView1);
profileIV=(ImageView)findViewById(R.id.imageView3);
vv = (VideoView)findViewById(R.id.your_video_view);
mainRel=(RelativeLayout)findViewById(R.id.main_rel);
recording_is_in_progress=false;
StopAnimation();
profileIV.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if(let_start_recording)
{
let_start_recording=false;
startIV.setImageResource(R.drawable.recorder_stop_circle);
startRecording();
recording_is_in_progress=true;
StartAnimation();
}
else
{
let_start_recording=true;
startIV.setImageResource(R.drawable.recorder_start_circle);
stopRecording();
recording_is_in_progress=false;
StopAnimation();//Stop Animation once we press button
}
}
});
//START & STOP Recording
startIV.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if(let_start_recording)
{
let_start_recording=false;
startIV.setImageResource(R.drawable.recorder_stop_circle);
startRecording();
recording_is_in_progress=true;
StartAnimation();
}
else
{
let_start_recording=true;
startIV.setImageResource(R.drawable.recorder_start_circle);
stopRecording();
recording_is_in_progress=false;
StopAnimation();//Stop Animation once we press button
}
}
});
}//EOF Oncreate
//(((( START ANIMATION ))))
public void StartAnimation()
{
// vv.setVisibility(View.VISIBLE);
startIV.setVisibility(View.VISIBLE);
mainRel.setVisibility(View.VISIBLE);
profileIV.setVisibility(View.GONE);
//Video Loop
vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
vv.start(); //need to make transition seamless.
}
});
// Uri uri = Uri.parse(R.drawable.sheep_video);
Uri uri= Uri.parse("android.resource://com.pac.myapp/raw/sheep_video");
vv.setVideoURI(uri);
vv.requestFocus();
vv.start();
vv.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.sheep_video));
vv.setOnPreparedListener(new OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mp.setLooping(true);
/// showtoast("video compelted");
}
});
}
public void StopAnimation()
{
if(vv.isPlaying())
vv.stopPlayback();
//vv.setVisibility(View.INVISIBLE);
startIV.setVisibility(View.GONE);
mainRel.setVisibility(View.INVISIBLE);
profileIV.setVisibility(View.VISIBLE);
}
private String getFilename()
{
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists())
{
file.mkdirs();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String filename = dateFormat.format(new Date());
filename="Voice "+filename+".wav";
return (file.getAbsolutePath() + File.separator + filename);
//return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".wav");
}
private void startRecording()
{
AudioSavePathInDevice = getFilename();
// 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();
}
}
private void stopRecording()
{
mediaRecorder.stop();
}
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 void onBackPressed()
{
if(recording_is_in_progress=true)
{
//if(recorder!=null)
//stopRecording();
finish();
}
}
public void home(View v)
{
//Intent i=new Intent(v.getContext(),MainActivity.class);
//startActivity(i);
//finish();
}
public void voice_list(View v)
{
if(recording_is_in_progress==false)
{
Intent i=new Intent(v.getContext(),SavedVoiceList.class);
startActivity(i);
finish();
}
}
public void about_us(View v)
{
//showtoast("status = "+recording_is_in_progress);
if(recording_is_in_progress==false)
{
Intent i=new Intent(v.getContext(),AboutUsActivity.class);
startActivity(i);
finish();
}
}
public void showtoast(String str)
{
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
}//EOF Activit
Probably you have to request a android.permission.RECORD_AUDIO permission to be able to record it after Android 6 version.
please check the document
I read through a tutorial and created a simple music player dubbed SimplePlayer. When I click the song I want to play, it plays perfectly fine.
However, when that song finishes, instead of playing the next song it plays the second song in the list, then keeps playing it over and over again.
I know that the choosing of the song when the first song finishes is inside the onCompletion method with the mp.setDataSource, but I'm not sure what I need to put in the brackets other than the +1 so that it plays the next song in the list:
public void onCompletion(MediaPlayer mp) {
try {
mp.reset();
mp.setDataSource(SD_PATH + songs.get(+1));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
Here is the rest of the code in case I have to change something there as well:
public class MainActivity extends ListActivity implements OnCompletionListener {
private static final String SD_PATH = new String(Environment.getExternalStorageDirectory().getPath() + "/");
private List<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
private View play;
private View pause;
private View stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updatePlaylist();
play = (ImageButton)findViewById(R.id.imageButton1);
pause = (ImageButton)findViewById(R.id.imageButton2);
stop = (ImageButton)findViewById(R.id.imageButton3);
mp.setOnCompletionListener(this);
play.setEnabled(false);
pause.setEnabled(false);
stop.setEnabled(false);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
try {
mp.reset();
mp.setDataSource(SD_PATH + songs.get(position));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
private void updatePlaylist() {
File home = new File(SD_PATH);
if (home.listFiles(new Mp3Filter()).length > 0) {
for (File file : home.listFiles( new Mp3Filter())) {
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_item,songs);
setListAdapter(songList);
}
}
public void play(View view){
Toast.makeText(getApplicationContext(), "Playing song",
Toast.LENGTH_SHORT).show();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
}
public void pause(View view){
Toast.makeText(getApplicationContext(), "Pausing song",
Toast.LENGTH_SHORT).show();
mp.pause();
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(true);
}
public void stop(View view){
Toast.makeText(getApplicationContext(), "Stopping song",
Toast.LENGTH_SHORT).show();
mp.stop();
play.setEnabled(false);
pause.setEnabled(false);
stop.setEnabled(false);
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
mp.reset();
mp.setDataSource(SD_PATH + songs.get(+1));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
}
also, how can I make it so that when the app runs, it lists all songs on the sdcard, the phone storage and in the folders on the sdcard? At the moment it only lists the songs on the root of the sdcard.
What you have written is for continuously playing second song.
You need to use a global variable to indicate song number and increment it and pass that to setDataSource();
First,create a public global variable
public static int SONG_NUMBER=0;
In your onCompletion method
#Override
public void onCompletion(MediaPlayer mp) {
try {
mp.reset();
if(SONG_NUMBER == songs.size())
{
SONG_NUMBER=0;
}
else
{
SONG_NUMBER=SONG_NUMBER+1;
}
mp.setDataSource(SD_PATH + songs.get(SONG_NUMBER));// pass SONG_NUMBER++ instead +1
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
In your on ListItemClick method,assign SONG_NUMBER based on position
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
try {
SONG_NUMBER=position; // <------------------------add this line
mp.reset();
mp.setDataSource(SD_PATH + songs.get(position));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
I'am trying to populate listview from audio files and want to play the clicked item. It's not working. Any help.
MainActivity.java
public class MainActivity extends ListActivity {
public static File file;
private List<String> filelist;
ArrayList<String> MyFiles = new ArrayList<String>();
MediaPlayer mp=new MediaPlayer();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
final ListView musiclist = (ListView) findViewById(R.id.PhoneMusicList);
MyFiles = new ArrayList<String>();
final String targetPath = Environment.getExternalStorageDirectory().getAbsolutePath();
file = new File( targetPath + "/AudioRecorder" ) ;
File list[] = file.listFiles();
// Binding resources Array to ListAdapter
for( int i=0; i< list.length; i++)
{
MyFiles.add( list[i].getName() );
}
ListAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, MyFiles);
musiclist.setAdapter(adapter);
musiclist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//checking the position of item in list
Object listItem = musiclist.getItemAtPosition(position);
Toast.makeText(MainActivity.this, ""+ musiclist, Toast.LENGTH_SHORT).show();
playSong(targetPath + MyFiles.get(position));
}
});
}
private void playSong(String songPath) {
// TODO Auto-generated method stub
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/PhoneMusicList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
This is my latest layout file:
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:id="#+id/PhoneMusicList"
android:layout_width="223dp"
android:layout_height="334dp" />
<ImageView
android:id="#+id/play_pause"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/pause"/>
I have created an already functioning app which displays ListView items and when an item in the list is selected, it then opens new activity. Inside the new_activity I have TextView and Image button displaying the audio buttons which is play, pause, & stop. the TextView functions perfectly but the image buttons refused to play audio file from raw folder. I have many audio files in the raw folder and want to assign each to each ListView that will open each new activity. Please help me edit this ListViewAdapter code below to play, pause, & stop playing each audio file.
How do I edit this NewActivity.java to populate it with songs from raw folder? I will highly appreciate your support thanks.
public class NewActivity extends AppCompatActivity {
private String TAG = "NewActivity ----- ; " ;
// Store instance variables
private String title;
private int page;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
ActionBar actionBar = getSupportActionBar();
TextView mDetailTv = findViewById(R.id.textView);
//get data from previous activity when item of activity is clicked using intent
Intent intent = getIntent();
String mActionBarTitle = intent.getStringExtra("actionBarTitle");
String mContent = intent.getStringExtra("contentTv");
//setctionBar Title
actionBar.setTitle(mActionBarTitle);
//get text in text textView
mDetailTv.setText(mContent);
//ok we are done,
public void play(View v) {
if (player == null) {
player = MediaPlayer.create(this, R.raw.song_1);
Toast.makeText(this, "Tune Playing", Toast.LENGTH_SHORT ).show();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer();
}
});
}
player.start();
}
public void pause(View v) {
if (player != null) {
player.pause();
Toast.makeText(this, "Tune Paused", Toast.LENGTH_SHORT ).show();
}
}
public void stop(View v) {
stopPlayer();
}
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Tune Stoped", Toast.LENGTH_SHORT ).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
}
Try with following code.
public class Recording_List extends Activity{
ListView mListView;
ImageView mPlayPause;
private File file;
private MediaPlayer mp = new MediaPlayer();
private Handler mHandler = new Handler();
private List<String> myList = new ArrayList<String>();
private static final String MEDIA_PATH = new String(
Environment.getExternalStorageDirectory() + "/AudioRecorder/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordlist);
mListView = (ListView) findViewById(R.id.recordList);
mPlayPause = (ImageView) findViewById(R.id.play_pause);
file = new File(MEDIA_PATH);
if (!file.exists()) {
file.mkdir();
}
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(MEDIA_PATH + myList.get(position));
}
});
mPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
mPlayPause.setImageResource(R.drawable.play);
}
} else {
if (mp != null) {
mp.start();
mPlayPause.setImageResource(R.drawable.pause);
}
}
}
});
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.release();
}
}
you should change targetPath as below
targetPath =targetPath + "/AudioRecorder/" ;
or replace
playSong(targetPath + MyFiles.get(position));
with
playSong(targetPath +"/AudioRecorder/"+ MyFiles.get(position));
Recorder With List View of that files in Ringa_Singa folder.
when you will stop the play you have to go back to update the list otherwise it's okay.
You can play the latest record from that play button
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_audio);
//List View
final ListView listView = (ListView) findViewById(R.id.listView);
myList = new ArrayList<String>();
//Recording events on button
startbtn = findViewById(R.id.btnRecord);
stopbtn = findViewById(R.id.btnStop);
playbtn = findViewById(R.id.btnPlay);
stopplay = findViewById(R.id.btnStopPlay);
stopbtn.setEnabled(false);
playbtn.setEnabled(false);
stopplay.setEnabled(false);
mFileName = Environment.getExternalStorageDirectory()+ "/RingaSinga";
int entryNumber = 1;
File mFile = new File(mFileName + "/RingaSinga_" + String.valueOf(entryNumber) + ".wav");
while (mFile.exists()) {
entryNumber++;
mFile = new File(mFileName + "/RingaSinga_" + String.valueOf(entryNumber) + ".wav");
}
this.mFileName = mFile.getAbsolutePath();
//List all files on list view
File directory = Environment.getExternalStorageDirectory();
mFile = new File( directory + "/RingaSinga" );
final File list[] = mFile.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, android.R.id.text1, myList);
listView.setAdapter(adapter); //Set all the file in the list.
//Click listner on List item
final File finalMFile = mFile;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(RecordAudio.this, ""+ listView, Toast.LENGTH_SHORT).show();
playSong(finalMFile + myList.get(position));
}
});
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CheckPermissions()) {
stopbtn.setEnabled(true);
startbtn.setEnabled(false);
playbtn.setEnabled(false);
stopplay.setEnabled(false);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(mFileName);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
} else {
RequestPermissions();
}
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopbtn.setEnabled(false);
startbtn.setEnabled(true);
playbtn.setEnabled(true);
stopplay.setEnabled(true);
mRecorder.stop();
mRecorder.release();
mRecorder = null;
Toast.makeText(getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
return;
}
});
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopbtn.setEnabled(false);
startbtn.setEnabled(true);
playbtn.setEnabled(false);
stopplay.setEnabled(true);
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
Toast.makeText(getApplicationContext(), "Recording Started Playing", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
});
stopplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.release();
mPlayer = null;
stopbtn.setEnabled(false);
startbtn.setEnabled(true);
playbtn.setEnabled(true);
stopplay.setEnabled(false);
Toast.makeText(getApplicationContext(), "Playing Audio Stopped", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_AUDIO_PERMISSION_CODE:
if (grantResults.length > 0) {
boolean permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean permissionToStore = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean permissionToRead = grantResults[2] == PackageManager.PERMISSION_GRANTED;
if (permissionToRecord && permissionToStore && permissionToRead) {
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean CheckPermissions() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED;
}
private void RequestPermissions() {
ActivityCompat.requestPermissions(RecordAudio.this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
}
private void playSong(String songPath) {
try {
mPlayer = new MediaPlayer();
mPlayer.reset();
mPlayer.setDataSource(songPath);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mPlayer.release();
}
I have an application that has a few buttons that have sounds (soundPool) I need to write them down on a flash card I make it through the MediaRecorder but when I run the app and then turn on the record playing and click stop recording application crashes you do not tell me what the problem is?
I expect that in the method recordStop
public class MainActivity extends Activity {
int kickSound;
SoundPool mSoundPool;
AssetManager assets;
private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
kickSound = loadSound("snare_trap.ogg");
ImageButton kick = (ImageButton)this.findViewById(R.id.imageButton1);
kick.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
playSound(kickSound);
}
return false;
}
});
fileName = Environment.getExternalStorageDirectory() + "/record.3gpp";
}
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Couldn't load file '" + fileName + "'", Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
}
public void recordStart(View v) {
try {
releaseRecorder();
File outFile = new File(fileName);
if (outFile.exists()) {
outFile.delete();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(AudioManager.STREAM_MUSIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(fileName);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void recordStop(View v) {
mediaRecorder.stop();
}
public void playStart(View v) {
try {
releasePlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileName);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void playStop(View v) {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}
private void releaseRecorder() {
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
}
private void releasePlayer() {
mediaPlayer.release();
mediaPlayer = null;
}
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
releaseRecorder();
}
}
Why are you releasing the recorder to start out with? Releasing should only be used if you don't want to access the recorder anymore. Try moving the release to the end.