Blog

Android: Saving a sound file to SD from resource and setting as ringtone

Quite a few people have been asking how to save a file to the SD card in order to register it as a ringtone. The following example creates a function that will save a resource to the SD card (ie: from R.raw.soundfile to /sdcard/media/audio/ringtones/soundfile.ogg) and register it as a ringtone.

I have split this example into two parts, the first part goes through the code a section at a time with a brief explanation of what it does, the second half is just the code that you can copy and paste and then edit to your hearts content.

Parts

We first setup our function to return a boolean depicting if we have failed or if we are successful. We accept in an integer which corresponds to the raw sound file.

public boolean saveas(int ressound){

}

So this function would be called in the following fashion:

saveas(R.raw.soundfile);

or utilising its boolean return:

if (saveas(R.raw.soundfile)){
// Code if successful
}
else
{
// Code if unsuccessful
}

The following chunk of code creates an inputstream from the raw sound resource and loads it into a buffer. We add in the mandatory try/catch clause around these operations and return false if an exception is raised (to indicate failure to the rest of our program and to prevent trying to continue act upon this sound).

 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;
 }

The following saves the buffer to a file on the SD card. It first ensures the folder exists and if not it is created. Then as before the writing operations are surrounded with try/catches

 String path="/sdcard/media/audio/ringtones/";
 String filename="examplefile"+".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;
 }    

The following code sends an intent to tell the Media Scanner that we have added a new file, and sets up its properties in the media database:

 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, "exampletitle");
 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
 values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
 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);

Final code
Putting all this code together gives us our final functions:

public boolean saveas(int ressound){
 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="examplefile"+".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, "exampletitle");
 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
 values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
 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);


 return true;
}

Comments, suggestions etc. are always welcome. Hope this has been helpful.

70 Comments

  1. […] This post was mentioned on Twitter by Planet Android, Matthew Rollings. Matthew Rollings said: Posted: Android: Saving a sound file to SD from resource and setting as ringtone http://bit.ly/cMwBSV […]

  2. Steve

    This is great I have this part working. Can you explain more about the context menu and how it knows what file per button?

  3. mat

    Ok sure that’s a good idea, I’ll write up a example tomorrow on using context menus.

  4. Steve

    Thanks!

    I expanded your saveas(); to include a string used for the soundname that can be used later in the code

    public boolean saveas(int ressound, String soundname){

    Is it a good idea to do that?

  5. mat

    Yes that’s a good idea. In my application I created two arrays one for the sound files and one for the names of the sound files. Then I simply passed my function an integer which corresponded to the file in one array and the matching text in the other array. This meant that I only needed to change the array’s if I were to change all the sound files.

  6. G

    Using this code, there seem to be two issues: (1) that the file appears as a ringtone, but with the filename and not the title as its menu title. (2) that i can’t seem to categorize it as a notification tone and not a ring tone. Any clues?

  7. G

    Looking into it a bit further, it seems that what really happens is that the MediaStore entry gets changed and erases the Title/Artist that is put in there and replaces it with /. Is anyone else experiencing this?

  8. mat

    That seems very weird I’ll do some testing soon to see if I can reproduce the problem,

  9. Chris

    just curious.. did you put all of this into a OnLongClick? if not how was the user able to select to save as ringtone?

  10. Jake

    Hi, im having problems getting this to work, it wont seem to copy the raw sound file to the sd card, I have tried adding the storage permissions but this hasnt helped. my raw files are either an .ogg or an .mp3 but this should still work? Thanks.

  11. Wildheart Baby

    I’d also like to know how I can utilise this code with an on long click button press, how would I implement it.

  12. mat

    @Chris, yes this was implemented onlong click where the can choose between a ringtone and a notification

    @Jake, It’s hard to help without knowing what the error is, can you check the logs (adb logcat) when the error occurs?

    @Wildheart Baby, you can override the default onCreateContextMenu in your activity and create a context menu and override the onContextItemSelected which then calls a function what to do based on which view the press originated (differentiate by the view’s ID). I will add a short write up of this soon.

  13. mat
  14. Jay

    It would be really nice if you could link the context menu guide and the save files to sd card guide.

    I am having trouble with my soundboard saving files…

  15. Chris

    hey matt..
    so we have a junk load of soundboards on the market now… but one main issue is after you save the sound file for notification or ringtone, if the phone loses power or something, then you have to re-save the sounds… our save code resembles yours very muhc, I was woundering if you’ve had this issue at all with yours?

  16. Colin

    Great stuff here, Matt. I really appreciate the info and the presentation.

    I have a question, though, and it might be super duper noobish.. which would equate to my level of Java skills pretty accurately. *sigh*

    Anyway here goes: I’ve got the onlongclick button working correctly, and I’ve implemented this code as well, I think correctly. When I run the app in a virtual machine, however, I get a force close when I try to click on my “save as ringtone” button in my onlongclick menu. is this merely because I am using a virtual machine without a space to store the sound file or is there something I’ve neglected in the code itself?

    I’m not sure if that made perfect sense, so I apologize if it was unclear or missing details.

    Again, this is a huge help for me as a Java beginner!

  17. mat

    Well to be completely sure what is causing your FC you should check logcat, but I agree with you if it tries to save to a place that doesnt exist, it will def force close. Please feel free to contact me via email in future as I will reply quicker

    android at stealthcopter.com

  18. Rosie

    Thank you so much!
    I have been struggling with how to play the music from my apk for 2 weeks! I’m using Processing with MediaPlayer and I was stumped; but a combination of your code and createInput() finally worked!

  19. udik

    great help thanks!!

    Quick question – it works perfect for ringtones, but for notifications I get exception when I try to invoke the Ringtone picker and click on this newly added entry (or any entry) – here is the exception, appriciate much any idea…

    07-22 15:51:03.241: ERROR/AndroidRuntime(316): Uncaught handler: thread main exiting due to uncaught exception
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:172)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.database.CursorWrapper.getString(CursorWrapper.java:135)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at com.android.internal.database.SortCursor.getString(SortCursor.java:205)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.media.RingtoneManager.getUriFromCursor(RingtoneManager.java:403)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.media.RingtoneManager.getRingtoneUri(RingtoneManager.java:399)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.media.RingtoneManager.getRingtone(RingtoneManager.java:382)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at com.android.internal.app.RingtonePickerActivity.run(RingtonePickerActivity.java:307)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.os.Handler.handleCallback(Handler.java:587)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.os.Handler.dispatchMessage(Handler.java:92)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.os.Looper.loop(Looper.java:123)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at android.app.ActivityThread.main(ActivityThread.java:4203)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at java.lang.reflect.Method.invokeNative(Native Method)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at java.lang.reflect.Method.invoke(Method.java:521)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
    07-22 15:51:03.271: ERROR/AndroidRuntime(316): at dalvik.system.NativeStart.main(Native Method)

  20. udik

    Never mind, need to add the following for notifcations:

    String path=”/sdcard/media/audio/notifications/”;

  21. Guto

    Hello,

    I like your code! I’m brazilian, so, excuse-me for my bad english! ;-D

    A question: The imput of this code is a audio file with extencion .RAW correct?

    The output is a new file equal the RAW but with .WAV estencion? And locate in local of I specified in the code in String path?

    If the two cases is corrects, I have problems… In final of the code probably, in the part of it create/write the new file…

    You can help me with this questions, please?

    Thanks!

  22. mat

    @Guto I had a mistake above, my files were ogg files in the /raw directory and my method copies byte-for-byte the file so the output too will be in ogg format. Does that answer your question?

  23. Guto

    Thanks mat. In this space of time I understand better about this informations…

    But I have other question:

    How I transform the code for that the sound file is no in raw directory, but in /sdcard/sound.wav, for example. I need more flexibility on entrance of data, but no find how!…

    I create a EditText for the user type the path of the file, but I no understand how modificate the code for this change…

    If you could help me, I thank you.

  24. Guto

    Someone can help me? I realy need this information.

    Tranks!

  25. Guto

    Hello someone?…

  26. Guto

    After days, I test more the code I have, and understand that I need transform a text of the EditText to a int, for after this put the int variable in the actual R.raw.soundfile local in the code.

    I no find how I do this.

    Someone can help me?

    Thanks!

  27. Sy

    Hi Matt, I have managed to integrate your saveas code into my sound board app without errors! (thanks for that btw) but how do I initiate it when the context menu selection is made? If I put your code anywhere within onContextItemSelected I just get errors, how do you piece it together please?

    Ta muchly, Sy

  28. Xero

    Thx

    Good job ๐Ÿ˜‰

  29. Xero

    And guys,

    don’t forget the permission on the Manifest file !

  30. s.avunoori

    Hi ,
    I am very new to android development.
    Thanks for your post on this topic of saving files from resources to sdcard.
    It worked for me great.

    Thank you very much.

    I hope you will post some more useful posts like this in future.

    Regards
    s.avunoori

  31. Richie

    It’s a nice tutorial.

    Do you how to save files from resources onto the sd card during installation. I’m developing a soundboard app. It has sound files of size 230Mb so i want to save them onto the sd card during installation.
    Please let me know how to do this.

    Regards
    Richie

  32. ramanathan

    Nice it helped me a lot.

    Thanks

  33. Digilife

    While the file copies only once regardless of the number of times the option to save it is selected the MediaStore TITLE gets created every time so when the user navigates to their settings for ringtone they are presented with a possibly endless number of instances of the TITLE.

    Has anyone else experienced this, if so how can it be resolved?

    Thanks

  34. mat

    Hey, sorry I don’t have time to answer all of your questions. Try posting on stackoverflow.com

    @richie an apk on google market can’t take up that much space, you should be downloading it once installed.

    @Digilife I’ve not seen this problem before but I can it makes sense. No idea how to solve, maybe stackoverflow could help ๐Ÿ˜›

  35. vamp6x6x6x

    I need your help I tried to add the following code to my button and nothing:

    public class MyMain extends Activity {
        /** Called when the activity is first created. */
    	@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            Button btn = (Button) findViewById(R.id.Button01);
            registerForContextMenu(btn);
        }
    
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
                    menu.setHeaderTitle("Context Menu");
                    menu.add(0, v.getId(), 0, "Action 1");
                    menu.add(0, v.getId(), 0, "Action 2");
            }
    
        @Override
            public boolean onContextItemSelected(MenuItem item) {
            if(item.getTitle()=="Action 1"){function1(item.getItemId());}
            else if(item.getTitle()=="Action 2"){function2(item.getItemId());}
            else {return false;}
            return true;
            }
    
        public void function1(int id){
            Toast.makeText(this, "function 1 called", Toast.LENGTH_SHORT).show();
        }
        public void function2(int id){
            Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();
        }
        
        public boolean saveas(int ressound){
        	 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="money"+".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, "exampletitle");
        	 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
        	 values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
        	 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);
    
        	 return true;
        	}
    
  36. mat

    @vamp6x6x6x You never call your saveas function but the toast messages should appear when you press the context menu items.

  37. vamp6x6x6x

    @mat toast messages do work 100% for me I just need to find a way to make it so it actually saves the ringtone.

  38. mat

    @vamp6x6x6x as I said above, you never call your save function. Also looks like you’ve added size=0 in which will cause pain. You could never write a file using an empty buffer.

  39. vamp6x6x6x

    @mat How do I call my save function in the toast and what should my buffer size be?

  40. mat

    @vamp6x6x6x to call a function you write the function name… perhaps you should go over a bit of basic java first?

  41. vamp6x6x6x

    @mat sorry for the trouble but could you give me like an example or something because see I learned half of what I know from youtube videos because I learn better by showing…and as far as I know there isn’t this situation on youtube.

  42. Chris

    I keep getting this error

    The method insert(Uri, ContentValues) is undefined for the type Object

  43. Prototype

    I have this:
    public class ProvaNotifica extends Activity {

    Button button1;
    MediaPlayer mp=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    button1 = (Button)this.findViewById(R.id.button1);

    button1.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {

    if(mp!=null){
    mp.release();

    }
    mp = MediaPlayer.create(getBaseContext(), R.raw.burp);
    mp.start();
    mp.setOnCompletionListener(new OnCompletionListener() {

    public void onCompletion(MediaPlayer mp) {
    mp.release();
    }

    });
    }

    });

    button1.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View view) {
    Boolean bool = saveas(R.raw.burp);
    if(bool){
    Toast.makeText(getBaseContext(), “Setted as ringtone”, 2).show();
    }else{
    Toast.makeText(getBaseContext(), “Error”, 2).show();
    }
    return true;
    }
    });

    }

    public boolean saveas(int ressound){
    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) {
    Toast.makeText(getBaseContext(), “Errore1”, 2).show();
    return false;
    }
    String path = “/sdcard/media/audio/ringtones/”;
    String filename = “burpfile”+”.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) {
    Toast.makeText(getBaseContext(), “Error 2”, 2).show();
    return false;
    } catch (IOException e) {
    Toast.makeText(getBaseContext(), “Error 3”, 2).show();
    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, “simpson”);
    values.put(MediaStore.MediaColumns.MIME_TYPE, “audio/ogg”);
    values.put(MediaStore.Audio.Media.ARTIST, “ciao”);
    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);

    return true;
    }
    }

    but it always show me the toast with the message Error 2 that corrisponds to the FileNotFoundException
    can anybody help?

  44. Tim

    Any chance I can still get help with this. My soundboard works great on one button, but my second will not work.

  45. Wil

    I keep getting the following error: The method getContentResolver() is undefined for the type new View.OnClickListener(){}

    Can you please help me with solving this issue please.

  46. mat

    Will, in my example the “this” is outside of any subclasses and so refers to my main class/activity you can replace this with the name of your class (the name of your java file).

  47. Paul

    Great example!! Has helped massively and very easy to follow. I was just wondering how you save multiple sounds? I have a soundboard with 18 sounds and would like to be able to save each sound separately. Many thanks.

  48. waseem sarwar

    Great tutorial i get the idea from here to write .svg file from resource to sdcard

  49. mrj05hua

    I have used your tutorial and its helped me alot, but I have read through each of your posts and I do not understand your using your Raw resources as integers or strings. I understand you can either put them into arrays as a global variable. I just don’t know how to do it in java, Everything works great in my app except I need to be able to pass the name of the raw resource to the saveas functions so it will save the file that is pressed.

    MediaPlayer player;

    	
    	/** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            
            //Coding for all buttons, registers, and Listeners
            Button btn1 = (Button) findViewById(R.id.btn1);
            registerForContextMenu(btn1); 
            btn1.setOnClickListener(this);
            Button btn2 = (Button) findViewById(R.id.btn2);
            registerForContextMenu(btn2);
            btn2.setOnClickListener(this);
            Button btn3 = (Button) findViewById(R.id.btn3);
            registerForContextMenu(btn3);
            btn3.setOnClickListener(this);
            Button btn4 = (Button) findViewById(R.id.btn4);
            registerForContextMenu(btn4);
            btn4.setOnClickListener(this);
            Button btn5 = (Button) findViewById(R.id.btn5);
            registerForContextMenu(btn5);
            btn5.setOnClickListener(this);
            Button btn6 = (Button) findViewById(R.id.btn6);
            registerForContextMenu(btn6);
            btn6.setOnClickListener(this);
            Button btn7 = (Button) findViewById(R.id.btn7);
            registerForContextMenu(btn7); 
            btn7.setOnClickListener(this);
            Button btn8 = (Button) findViewById(R.id.btn8);
            registerForContextMenu(btn8);
            btn8.setOnClickListener(this);
            Button btn9 = (Button) findViewById(R.id.btn9);
            registerForContextMenu(btn9);
            btn9.setOnClickListener(this);
            
           
            
        }//closes OnCreate
        
        //On click Handlers for multiple buttons 
        public void onClick(View v) {
        	switch(v.getId()){
        	case R.id.btn1:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.boomstick);
        		player.start();
        		
        		break;
        	case R.id.btn2:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.shebitch);
        		player.start();
        		
        		break;
        	case R.id.btn3:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.chainsaw);
        		player.start();
        		
        		break;
        	case R.id.btn4:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.boomstick);
        		player.start();
        		
        		break;
        	case R.id.btn5:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.shebitch);
        		player.start();
        		
        		break;
        	case R.id.btn6:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.chainsaw);
        		player.start();
        		
        		break;
        	case R.id.btn7:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.boomstick);
        		player.start();
        		
        		break;
        	case R.id.btn8:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.shebitch);
        		player.start();
        		
        		break;
        	case R.id.btn9:
        		// action to perform on button 1
        		
        		player = MediaPlayer.create(this, R.raw.chainsaw);
        		player.start();
        		
        		break;
        	}
        }//closes onClick
        
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    		menu.setHeaderTitle("Save As ");
    		menu.add(0, v.getId(), 0, "Ringtone");
    		menu.add(0, v.getId(), 0, "Notification");
    		menu.add(0, v.getId(), 0, "Alarm");
    	}//closes onCreateContextMenu
    
        @Override
    	public boolean onContextItemSelected(MenuItem item) {
           	if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
        	else if(item.getTitle()=="Notification"){function2(item.getItemId());}
        	else if(item.getTitle()=="Alarm"){function3(item.getItemId());}
        	else {return false;}
    	return true;
    	}//Closes MenuItems
        
    	public void function1(int id){
    		saveasRing(R.raw.shebitch);
        	Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
        }//Closes Function 1
        public void function2(int id){
        	saveasNotifications(R.raw.shebitch);
        	Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
        }//closes Function 2
        public void function3(int id){
        	saveasAlarm(R.raw.shebitch);
        	Toast.makeText(this, "Saved as Alarm", Toast.LENGTH_SHORT).show();
        }//Closes Function 3
        
        //Save as Ringtone Coding for Function 3
        public boolean saveasRing(int ressound){
        	 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= "shebitch" +".mp3";
    
        	 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, "exampletitle");
        	 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
        	 values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
        	 values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        	 values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        	 values.put(MediaStore.Audio.Media.IS_ALARM, false);
        	 values.put(MediaStore.Audio.Media.IS_MUSIC, false);
    
        	 //Insert it into the database
        	 this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
    
    
        	 return true;	
        }//Closes Save as Ringtone 
    

    Where or how do I set up the function call for it to have the int and then check for the saveas filename and change the name upon which file is playing

  50. mat

    All your R.raw.chainsaw etc… those are integers.

Leave a Comment

Your email address will not be published. Required fields are marked *