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.
Related
How do I play an audio from raw folder on button click? Here, I'm using recyclerview to show the list of audios. But when click play, it doesn't play any sound.
private Button btnPlay;
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = new MediaPlayer();
try{
mp.setDataSource(ss.getSoundURI());
mp.prepare();
mp.start();
} catch (Exception e){
e.printStackTrace();
}
}
});
You can use this function:
public void playSound(final String fileName) {
MediaPlayer mpPlayer = null;
try {
int fileId = getResources().getIdentifier(fileName, "raw", getPackageName());
mpPlayer = MediaPlayer.create(this, fileId);
mpPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mpPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (Exception e) {
e.printStackTrace();
if (mpPlayer != null)
mpPlayer.release();
}
}
NOTE: use file name without file extension. for example if your file name is file1.wav you should send file1 as a file name to function NOT file1.wav .
NOTE: In first line I defined the mpPlayer and initialize it because i want to use it in the catch block.
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();
Sorry for my english is not good.
I have a problem, i download image from url by using picasso library, then store it in sdcard, but i can't see it in sdcard, and i only see it when i restart my phone, here is my code, what i do wrong??? help me, please !!!
public class Image extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_show_image);
Intent it = getIntent();
Bundle bundle = it.getExtras();
final String link = bundle.getString("link");
final ImageView ivView = (ImageView) findViewById(R.id.ivView);
Picasso.with(getApplicationContext()).load(link).into(ivView);
Button btSetWallpaper = (Button) findViewById(R.id.btSetWallpaper);
btSetWallpaper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadImage(link);
}
});
}
public void downloadImage(final String link){
Picasso.with(getApplicationContext()).load(link).into(new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/abc.jpg");
try {
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
}
catch (Exception e){
e.getStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Success" + Environment.getExternalStorageDirectory().getPath(), Toast.LENGTH_LONG).show();
}
#Override
public void onBitmapFailed(Drawable drawable) {
Toast.makeText(getApplicationContext(), "Load Fail", Toast.LENGTH_LONG).show();
}
#Override
public void onPrepareLoad(Drawable drawable) {
}
});
}
}
You need to tell Android Media Library that a media file has been added.
Intent intent =
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
Replace the file with your saved file and it should appear in your Android Media Library without rebooting the phone.
You need to tell the system to run a media scanner and only then the file will appear in the gallery. Which can be done as follows:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
OR
MediaScannerConnection.scanFile(this,
new String[] { filepath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// your code here
}
});
I'm develop some app with recording voice function and I just want to save it on my external storage, now I know how to save it without a folder but I want that my app creates unique folder for the files I recorded
my code:
public class MainActivity extends Activity {
MediaRecorder recorder = null;
MediaPlayer player = null;
public static String OUTPUT_FILE;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"audiorecorder.acc";
}
public void record(View v) {
try {
beginRecording();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
public void stop(View v) {
stopRecording();
}
public void play(View v) {
try {
beginPlay();
} catch (IllegalArgumentException | SecurityException
| IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlayback(View v) {
StopPlay();
}
private void beginRecording() throws IllegalStateException, IOException {
dictchMediaRecorder();
File file = new File(OUTPUT_FILE);
if(file.exists()){
file.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
recorder.setAudioEncodingBitRate(9600);
recorder.setAudioSamplingRate(44100);
recorder.setOutputFile(OUTPUT_FILE);
recorder.prepare();
recorder.start();
}
private void beginPlay() throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
ditchMediaPlayer();
player = new MediaPlayer();
player.setDataSource(OUTPUT_FILE);
player.prepare();
player.start();
}
I'm only added this lines and it's work perfect:
File dir_image;
public static String OUTPUT_FILE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dir_image = new File(Environment.getExternalStorageDirectory()+File.separator+"folderName");
dir_image.mkdirs();
OUTPUT_FILE = dir_image.getPath()+"/acapella.wav";
Add this :
private File dir_image;
String myfile="the name of the song.acc";
dir_image = new File(Environment.getExternalStorageDirectory()+
File.separator+"The name of your folder");
dir_image.mkdirs();
File tmpFile = new File(dir_image,myfile);
I'd like to add that you need to add the following to your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Or try to add this to your code :
instead of this :
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"audiorecorder.acc";
try :
OUTPUT_FILE = Environment.getExternalStorageDirectory()+
File.separator+"The name of your folder"+
File.separator+"audiorecorder.acc";
I need help/pointer to doc/sample code on how to load multiple audio files from a specific folder on the SD card and have it play a random file back(i think i can figure out the last step if i could just figure out how to load multiple files). Here is my incredibly poorly written app so far, don't judge too harshly as I'm learning as I go.
public class zazenbox extends Activity implements OnClickListener{
File filecheck;
MediaPlayer player;
Button playerButton;
Integer var1;
String path1;
AlertDialog.Builder alertbox;
public void onClick(View v) {
if (v.getId() == R.id.play) {
playPause();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
demoLoad();
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop);
playerButton.setOnClickListener(this);
demoPlay();
}
#Override
public void onPause() {
super.onPause();
player.pause();
}
#Override
public void onStop() {
super.onStop();
player.stop();
}
private void demoLoad() {
dirfilecheck();
player = new MediaPlayer();
player.setLooping(true);
try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }
}
private void dirfilecheck() {
filecheck = new File(Environment.getExternalStorageDirectory() + "/zazenbox");
if(filecheck.exists() && filecheck.isDirectory()) {
// load files.
var1 = 1;
path1 = filecheck + "/bm10" + var1 + ".wav";
} else {
// create folder, dl sample loop, and instruct user how to add music/loops.
filecheck.mkdirs();
alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Please put loopable media in zazenbox on your sdcard.");
alertbox.setNeutralButton("Ok, I will.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "Please plug in your device now", Toast.LENGTH_LONG).show();
}
});
alertbox.show();
}
}
private void demoPause() {
player.pause();
playerButton.setText(R.string.play);
}
private void demoStop() {
player.stop();
playerButton.setText(R.string.play);
}
private void demoPlay() {
player.start();
playerButton.setText(R.string.stop);
}
private void playPause() {
if(player.isPlaying()) {
demoStop();
//demoPause();
//player.release();
var1++;
path1 = filecheck + "/bm10" + var1 + ".wav";
/*try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }*/
//player.start();
//demoPlay();
} else {
//do stuff
demoPlay();
}
}
}
Memory is extremely limited on mobile devices, so you wouldn't want to load songs you're not going to play. So what you should do is find all of the audio files in that folder, and then choose one and THEN load and play it.
You just need to stop the current player and create a new instance.
MediaPlayer player = MediaPlayer.create(this, Uri.parse("Path/To/Media"));
player.start();
// change track
player.stop();
player = MediaPlayer.create(this, Uri.parse("New/Path/To/Media"));
player.start();