Random sound onclick button android assets - android

I want to play random sounds from assets/ folder in my project.
What's wrong with that code? Help me please
Here's my code:
MediaPlayer player;
AssetFileDescriptor descriptor;
private String[] filelist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
Button bTutorial1 = (Button) findViewById(R.id.tutorial1);
AssetManager aMan = this.getAssets();
try {
filelist = aMan.list("mysounds/");
// OR
// filelist = aMan.list("/");
} catch (IOException e1) {
e1.printStackTrace();
{
}
bTutorial1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(filelist.length);
try {
String mediaFile = filelist[randomInt];
descriptor = getAssets().openFd(mediaFile);
player.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(),
descriptor.getLength());
descriptor.close();
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
After click on the button nothing sound is playing. Help me!
No errors displays.

Try this Mediaplayer constructor:
MediaPlayer player = MediaPlayer.create(Context context, Uri uri);
uri = Uri.parse("file:///android_asset/mysounds/music.mp3");

Related

Android MediaPlayer stops palyng form assetst after changing image on button from assets

I have problem with playing mp3 from asset folder. When i try to change image on button, mp3 stops playing(not always...)
Error that im getting
W/MediaPlayer-JNI: MediaPlayer finalized without being released
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(enableMusic){
playMusic();
}
...
private void playMusic() {
boolean noAudioFile = false;
Context context = this; // or ActivityNotification.this
MediaPlayer mpMusic = new MediaPlayer();
AssetManager mg2 = getResources().getAssets();
String musicPath = langFolder+audioFolder+"system/Bubble_Bath.mp3";
try {
mg2.open(musicPath);
} catch (IOException ex) {
noAudioFile = true;
}
if(!noAudioFile) {
AssetFileDescriptor descriptor = null;
try {
descriptor = context.getAssets().openFd(musicPath);
} catch (IOException e) {
e.printStackTrace();
}
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
try {
mpMusic.setDataSource(descriptor.getFileDescriptor(), start, end);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
}
mpMusic.setVolume(5,5);
try {
mpMusic.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mpMusic.start();
mpMusic.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.start();
}
});
}
public void nextCard(View view) throws IOException {
i++;
if (i==files.length) i=0;
if(i>-1){
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setText("Next");
}
Drawable d = Drawable.createFromStream(getAssets().open(categoryPath+"/"+files[i]+".png"), null);
findViewById(R.id.btnImage).setBackgroundDrawable(d);
if(files[i].substring(0,1).contains("a") || files[i].substring(0,1).contains("i")){
startFileSound = langFolder + audioFolder + "system/GAME_thisisan.mp3";
}
else if (files[i].substring(files[i].length()-1,files[i].length()).contains("s")){
startFileSound = langFolder + audioFolder + "system/GAME_theseare.mp3";
}
else{
startFileSound = noAudioFileSound;
}
}
When i'll try to comment line below, mp3 is playing with no problem.
Drawable d = Drawable.createFromStream(getAssets().open(categoryPath+"/"+files[i]+".png"), null);
you are loading drawable from asset folder, that is correct. But Don't do in the main thread. Try to do this in different thread.
Don't ever create MediaPlayer like this
MediaPlayer mpMusic = new MediaPlayer();
Use
MediaPlayer.create(context,R.raw.music);
try close descriptor
mpMusic.setDataSource(descriptor.getFileDescriptor(), start, end);
descriptor.close();

How can I save multiple audio files?

I just started working on an audio recorder app. So far, the app can record audio and play it. My end goal is to be able to save multiple audio files to the device. How would I do this? Can I use SharedPreferences? I haven't been able to find anything.
public class MainActivity extends AppCompatActivity {
Button play;
Button stop;
Button record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Create a folder in your external storage and store each file with a timestamp appended to the name of the file.
You can list all the video / audio files stored in this folder and select which video / audio you want to play anytime.
Get all files
public void displayAllFilesInFolder() {
List<String> filepath = new ArrayList<String>();
if (!hasSDCard()) {
return;
}
File dir = new File(android.os.Environment.getExternalStorageDirectory() + "folderName");
if (!dir.exists()) {
return;
}
File listAllFiles[] = dir.listFiles();
if (listAllFiles != null) {
for (int i = 0; i < listAllFiles.length; i++) {
if (!listAllFiles[i].isDirectory()) {
filepath.add(listAllFiles[i].getAbsolutePath());
}
}
}
}
Check if SD is mounted
private boolean hasSDCard(){
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent) {
return true;
}
else{
return false;
}
}
You're already saving it to a file:
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
You just need to add more logic to pick a filename that doesn't already exist.

Download non-latin script language file from google translate

I'm trying to download a mp3 file generated with google translate. It works fine with languages with Latin script, but if I for example try Thai it dosen't work at all.
Any one have a suggestion? This is my code:
public class MyActivity extends Activity {
private Button mButton;
private File mOutputFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
new Thread(new Runnable() {
#Override
public void run() {
String uri = Uri.parse("http://translate.google.com/translate_tts")
.buildUpon()
.appendQueryParameter("tl", "th")
.appendQueryParameter("q", "ก")
.build().toString();
mOutputFile = new File(getFilesDir(), "sound.mp3");
try {
new DefaultHttpClient().execute(new HttpGet(uri))
.getEntity().writeTo(
new FileOutputStream(mOutputFile));
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
mButton = (Button) findViewById(R.id.speak);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play(mOutputFile.getAbsolutePath());
}
});
}
private void play(String path) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found out awhile ago and remember I should post my findings. I needed to add another parmeter to the url:
.appendQueryParameter("ie", "utf-8")
Now it works perfect.

How to play random sound form assets folder on button click?

I need to play random sound out of 300 sounds placed in assets folder.
While implementing the problem I am getting is that its always playing the first sound from assets on button click.
MediaPlayer player;
AssetFileDescriptor descriptor;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.machine);
player = new MediaPlayer();
playSound = (ImageButton)findViewById(R.id.button_play);
AssetManager aMan = this.getAssets();
try
{
filelist = aMan.list("");
} catch (IOException e1) {
e1.printStackTrace();
}
playSound.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(filelist.length);
try
{
String mediaFile = filelist[randomInt];
descriptor = getAssets().openFd(mediaFile);
player.setDataSource(descriptor.getFileDescriptor(),descriptor.getStartOffset(),descriptor.getLength());
descriptor.close();
player.prepare();
player.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
Try changing this line:
filelist = aMan.list("");
to this:
filelist = aMan.list("/assets");

How to play 3gp audio file in Android using default player in the device?

I need to play an 3gp audio file stored in my sd card location, to play it with my default media player in my HTC device.
Code :
public class AudioRecorder extends Activity {
private static final String CAMERA_STATUS = "camera_upload";
private static final String GALLERY_STATUS = "gallery_upload";
MediaRecorder recorder = new MediaRecorder();
static String path = "audio-android.3gp";
Button startRecording;
Button stopRecording;
Button save;
Button palyAudio;
private Context context;
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_recording);
context = this;
/**
* Creates a new audio recording at the given path (relative to root of
* SD card).
*/
this.path = sanitizePath(path);
startRecording = (Button) findViewById(R.id.startRecording);
stopRecording = (Button) findViewById(R.id.stopRecording);
save = (Button) findViewById(R.id.resetRecording);
palyAudio = (Button) findViewById(R.id.playRecorded);
startRecording.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
stopRecording.setVisibility(View.VISIBLE);
startRecording.setVisibility(View.GONE);
start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
stopRecording.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
stopRecording.setVisibility(View.GONE);
startRecording.setVisibility(View.VISIBLE);
try {
stop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
palyAudio.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
playAudio();
//startMediaPlayer();
}
});
}
/**
*
* play the recorded audio
*
*/
public void playAudio() {
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse(path);
// Intent intent = new Intent(Intent.ACTION_VIEW, data);
intent.setDataAndType(data, "audio/mp3");
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* Starts a new recording.
*/
public void start() throws IOException {
recorder = new MediaRecorder();
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
System.out.println("start() directory > " + directory);
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
/**
* Stops a recording that has been previously started.
*/
public void stop() throws IOException {
recorder.stop(); // Stops recording.
recorder.release(); // Now the object cannot be reused
}
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(t);
path = "/sdcard/sample.mp3";
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
So this is actually quite a headbanger, but here's how to do it:
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + yourfilepath);
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setDataAndType(uri,"video/3gpp");
startActivity(it);
The key is to set the video MIME, even for the audio file. Don't ask me why this works, it just does.
Uri playUri = Uri.parse("file:///sdcard/music/an.mp3");
Intent intent = new Intent(Intent.ACTION_VIEW, playUri);
startActivity(intent);
Use VideoView (see example) to get over the use of surface and states, it uses the native player.
String path = getExternalStorageDirectory() + "/path/to/file/in/sdcard";
VideoView vv = (VideoView)findViewById(R.id.myVideoViewId);
vv.setVideoPath(path);
vv.start();
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse("file:///sdcard/sample.mp3");
intent.setDataAndType(data,"audio/mp3");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}

Categories

Resources