Wednesday, June 29, 2011

Save as Ringtone Android Dev

The biggest trouble i had with my louis soundboard was getting the "Save as ringtone or notification" feature to work with my sound files.

This page from Stealthcopter helped me greatly. This sweet guy did basically all the work for me, the only problem was that it didn't work straight out of the box for me. After much trial and error, the only way i could get it to work was by adding a switch statement for each of my raw sound files, cumbersome and an example of very poor coding yes, but it works!

e.g.


public boolean saveas(int ressound){
String soundname = "";
switch(ressound){
case R.id.sound1:
ressound = R.raw.sound1;
soundname = "louis1";
break;
}

switch(ressound){
case R.id.sound3:
ressound = R.raw.sound3;
soundname = "louis3";
break;
}
//and so on and so on.....
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;

try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}

String path="/sdcard/media/audio/ringtones/";
String filename=soundname+".ogg";

boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}

FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

File k = new File(path, filename);

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, soundname);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "Louis CK ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);

//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);


String i = "Saved";
Toast.makeText(getApplicationContext(), i,
Toast.LENGTH_SHORT).show();
return true;
}

No comments:

Post a Comment