Related
So i'm trying to set an audio file located in the raw as a ringtone and then saving it to my sdcard. The current code seems to save a file, but that file plays some generic ringtone as opposed to the sound I'm trying to get it to play. What's the issue with it?
String exStorePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = exStorePath + "/media/ringtone/";
File k = new File(path, "wearenumberone.mp3");
Uri mUri = Uri.parse("android.resource://com.example.matig.mlgsoundboarddeluxe/" + R.raw.wearenumberone);
ContentResolver mCr = SoundActivity1.this.getContentResolver();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "NUMBERONE2");
values.put(MediaStore.MediaColumns.SIZE, k.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "guy");
values.put(MediaStore.Audio.Media.DURATION, 230);
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);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(SoundActivity1.this, RingtoneManager.TYPE_RINGTONE, newUri);
Settings.System.putString(mCr,Settings.System.RINGTONE,newUri.toString());
Toast.makeText(SoundActivity1.this,"done",Toast.LENGTH_SHORT).show();
try this
File file = new File(Environment.getExternalStorageDirectory(),
"/myRingtonFolder/Audio/");
if (!file.exists()) {
file.mkdirs();
}
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/myRingtonFolder/Audio/";
File f = new File(path + "/", name + ".mp3");
Uri mUri = Uri.parse("android.resource://"
+ context.getPackageName() + "/raw/" + name);
ContentResolver mCr = context.getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(f);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, f.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, name);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, f.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
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, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(f
.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(context,
RingtoneManager.TYPE_RINGTONE, newUri);
Settings.System.putString(mCr, Settings.System.RINGTONE,
newUri.toString());
} catch (Throwable t) {
}
I made my app to get file from Raw folder and set that file as Ringtone.
But there is a problem, the file is created and set as ringtone: http://prntscr.com/2so80e
But file does not have any sound, and idk why I am guessing by default my device is playing another ringtone.
Here is my code:
case 64:
String path = "android.resource://" + getPackageName() + "/"+R.raw.fusrodah;
File k= new File(path);
Log.i("OUTPUT", path);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k .getPath());
values.put(MediaStore.MediaColumns.TITLE, "Fusrodah File");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "Testing");
values.put(MediaStore.MediaColumns.SIZE, 215454);
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);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(Context.this,
RingtoneManager.TYPE_RINGTONE, newUri);
break;
What Am I doing wrong?
Is there something that I am missing?
I have all permissions, file is created but doesn't have any sound.
It looks like you should copy your file to SD-card firstly, then use this copy as ringtone. Here full code sample (I have file "kalimba.mp3" in my assets):
private int size;
private static final int BUFFER_LEN = 1024;
private void copyFile(AssetManager assetManager, String fileName, File out) throws FileNotFoundException, IOException {
size = 0;
FileOutputStream fos = new FileOutputStream(out);
InputStream is = assetManager.open(fileName);
int read = 0;
byte[] buffer = new byte[BUFFER_LEN];
while ((read = is.read(buffer, 0, BUFFER_LEN)) >= 0) {
fos.write(buffer, 0, read);
size += read;
}
fos.flush();
fos.close();
is.close();
}
#Override
public void onClick(View arg0) {
AssetManager assetManager = getAssets();
File file = new File(Environment.getExternalStorageDirectory(),
"/myRingtonFolder/Audio/");
if (!file.exists()) {
file.mkdirs();
}
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/myRingtonFolder/Audio/";
File out = new File(path + "/", "kalimba.mp3");
if(!out.exists()){
try {
copyFile(assetManager, "kalimba.mp3", out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, out.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "name");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, out.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
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, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(out.getAbsolutePath());
ContentResolver mCr = getContentResolver();
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
Settings.System.putString(mCr, Settings.System.RINGTONE,
newUri.toString());
}
catch (Throwable t)
{
//TODO Handle exception
}
}
I am developing an application: I am trying to set an audio file as a ringtone.
I saw many posts, but no one actually helped me, so I decided to ask this question.
I use this code when the Button is clicked:
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(Intent.createChooser(intent, "Choose Sound File"), Audio);
}
in onActivityResult I am trying to get the file path and then set the audio file as ringtone using the code below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Audio && requestCode==RESULT_OK) {
Uri s1 = data.getData();
String s = s1.getPath();
if(s!=null){
try {
k = new File(new URI(s)); //(File k;)
} catch (URISyntaxException e) {
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.ARTIST, "Some Artist");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
MainActivity.this,
RingtoneManager.TYPE_RINGTONE,
newUri);
}
}
}
Unfortunately this code doesn't work.
I would appreciate your answers. Sorry for my bad English.
I saw many posts but anyone showed what i should actually have to do. So i decided to create this complete answer , in which i have the solution of my problem...
Here is my MainActivity.java which i used
import java.io.File;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
b = (Button) findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent();
intent1.setAction(Intent.ACTION_GET_CONTENT);
intent1.setType("audio/*");
startActivityForResult(
Intent.createChooser(intent1, "Choose Sound File"), 6);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 6) {
Uri i = data.getData(); // getData
String s = i.getPath(); // getPath
File k = new File(s); // set File from path
if (s != null) { // file.exists
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "ring");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, k.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
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);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath());
getContentResolver().delete(
uri,
MediaStore.MediaColumns.DATA + "=\""
+ k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(
MainActivity.this, RingtoneManager.TYPE_RINGTONE,
newUri);
} catch (Throwable t) {
}
}
}
}
}
Lastly, its really important to add those permissions in your AndroidManifest.xml for example if you don't add the permission to write external storage your app will crash like mine.. xD
What you need:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
You can try my app on Google Play : BackAtel Audio Manager
Hope that helps.... my problem is now solved!! i hope that i solved your problem too :))
I had the same problem and couldn't find an answer anywhere.
This is the code i used.
#SuppressLint("SdCardPath")
public class Content extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order, e.g. button01 is tied to back to you
final int[] buttonIds = { R.id.Button01, R.id.Button02, R.id.Button03, R.id.Button04, R.id.Button05, R.id.Button06,R.id.button1};
final int[] soundIds = { R.raw.deargod, R.raw.donttalk, R.raw.lookat, R.raw.stop, R.raw.text,R.raw.john, R.raw.sherlock, };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
// new code to prevent crash is below.
if(soundButton!= null)
{
selectedSoundId = soundIds[1];
}
}
}
#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");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
else if(item.getTitle()=="Notification"){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
if
(savering(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if
(savenot(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
//Save into Ring tone Folder
public boolean savering(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=50;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path="/sdcard/sounds/";
String filename="Sherlock"+".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
} catch (IOException e) {
// TODO Auto-generated catch block
}
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, "SHRingtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "Sherlock ");
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);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
return true;
}
//Save in Notification Folder
#SuppressLint("SdCardPath")
public boolean savenot(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=50;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path="/sdcard/sounds/";
String filename="Sherlock"+".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
} catch (IOException e) {
// TODO Auto-generated catch block
}
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, "SHNotification");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "sherlock ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, newUri);
return true;
}
}
setting audio as a ringtone is the same as setting tone in alarm heres the code:
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.MediaColumns.DATA, path+audioname );
values.put(MediaStore.MediaColumns.TITLE, path+audioname );
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
//new
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, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
///new
// values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
// ContentResolver contentResolver = getContentResolver();
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(path+audioname), values);
//RingtoneManager.setActualDefaultRingtoneUri(Activity.this,
// RingtoneManager.TYPE_RINGTONE, newUri);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+path+audioname
+ Environment.getExternalStorageDirectory())));
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+editText1)));
//Toast.makeText(this, "New Alarm Sound " + editText1 +format, Toast.LENGTH_LONG).show();
}
using this code it allows your sound to be put in specific sd card folders and then setting it as ringtone and alarmtone:
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
or you can follow a complete tutorial regarding this problem.
I created a test project with a methed called testringtone(), that sets a ringtones. It ran fine. When I copied this method in another project, I get a error thats says RingtunesstarwarsActivity cannot be resolved to a type, the line is
RingtunesstarwarsActivity.this.getPackageName()+ "/" + "raw/blasters";
Uri mUri = Uri.parse(strUri);.
This works fine in my test project.
complete
method void testringtone()
{
File newSoundFile = new File("/sdcard/", "myringtone.oog");
ERROR HERE ///////////////////////////////////////////////////
String strUri = "android.resource://"+
RingtunesstarwarsActivity.this.getPackageName()+ "/" + "raw/blasters";
Uri mUri = Uri.parse(strUri);
/////////////////////////////
ContentResolver mCr = getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile= mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile=null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
//////////////////////////////////////////
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/oog");
values.put(MediaStore.MediaColumns.SIZE, newSoundFile.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
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);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(newSoundFile.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);
} catch (Throwable t) {
// Log.d(TAG, "catch exception");
}
///////////////////////////////////////
} // end methed
It seems like you forgot to rename your code to reference your new actvity. Sounds like RingtunesstarwarsActivity is part of the old code and you haven't done the refactoring needed to bring everything up to date.
Either way, I don't even think you need the ClassName.this prefacing getPackageName() unless testringtone() is inside an inner class of some sort, such as an onClickListener.
I'm trying to find a way to set a new default ringtone by code from my Android activity.
I have already downloaded the ringtone into a bytearray.
Finally, I managed to set the default ringtone to one that i downloaded.
The download code is not included below, only what was needed to set it as default ringtone.
File k = new File(path, "mysong.mp3"); // path is a file to /sdcard/media/ringtone
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.SIZE, 215454);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "Madonna");
values.put(MediaStore.Audio.Media.DURATION, 230);
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
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri = this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
myActivity,
RingtoneManager.TYPE_RINGTONE,
newUri
);
Anyway, I do not totally understand what this code is doing.
The Ringtone manager needs a uri to the file that is to be set as new ringtone. But this uri can not be directly to the sdcard like "/sdcard/media/ringtones/mysong.mp3". That does not work!
What you need is the external file uri of the file which could be something like
"/external/audio/media/46"
The 46 is the id of the column in the MediaStore database, so thats why you need to add the sdcard file into the database first.
Anyway, how does mediastore maintain its ids? This number can get really high, as you do this operation many times.
Do i need to delete this row my self? Problem is that some times i dont even controll the deleting of the file since it can be deleted directly from the sdcard with a filebrowser.
Answer By Vidar is too long and it adds duplicate entries every time you want to set a song as ringtone . Instead you should try this
Uri newUri=Uri.parse("content://media/external/audio/media/"+ID);
try {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}
catch (Throwable t) {
}
public void setRingtone() {
String ringtoneuri = Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/ringtone";
File file1 = new File(ringtoneuri);
file1.mkdirs();
File newSoundFile = new File(ringtoneuri, "myringtone.mp3");
Uri mUri = Uri.parse("android.resource://globalapps.funnyringtones/raw/sound_two.mp3");
ContentResolver mCr = this.getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, newSoundFile.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
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);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(newSoundFile.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
try {
Uri rUri = RingtoneManager.getValidRingtoneUri(this);
if (rUri != null)
ringtoneManager.setStopPreviousRingtone(true);
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
Toast.makeText(this, "New Rigntone set", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
Log.e("sanjay in catch", "catch exception"+e.getMessage());
}
}
You can use the built-in RingtonePreference class. AndroidGuys has a nice tutorial on this here.
This is the code i used! i hope it helps..
This is also the link.
String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String path=(exStoragePath +"/media/alarms/");
saveas(RingtoneManager.TYPE_RINGTONE);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+path+filename+".mp3"
+ Environment.getExternalStorageDirectory())));
File k = new File(path, filename);
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.MediaColumns.DATA, path + filename );
values.put(MediaStore.MediaColumns.TITLE, filename );
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
//new
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, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
this.getContentResolver()
.insert(MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath()), values);
HAPPY CODING!
I cannot comment the solution because I don't have enough reputation on stack overflow ... I want just add a way to add the audio file into media database without accessing directly to the database and hence avoiding to get duplicates.
The solution is based on MediaScannerConnection, this is the code I used:
String[] files = { audioFullPath };
MediaScannerConnection.scanFile(
getApplicationContext(),
files,
null,
new OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.v("myapp", "file " + path + " was scanned seccessfully: " + uri);
}
}
);
provide intent for ringtone selection.
final Uri currentTone= RingtoneManager.getActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_ALARM);
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentTone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
startActivityForResult(intent, 999);
then catch the result of selection in onActivityResult.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 999 && resultCode == RESULT_OK){
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
txtView.setText("From :" + uri.getPath());
//Set selected ringtone here.
RingtoneManager.setActualDefaultRingtoneUri(
this,
RingtoneManager.TYPE_RINGTONE,
uri
);
}
}
I have try these code its help
private void setRingtone(Context context, String path) {
if (path == null) {
return;
}
File file = new File(path);
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
String filterName = path.substring(path.lastIndexOf("/") + 1);
contentValues.put(MediaStore.MediaColumns.TITLE, filterName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
contentValues.put(MediaStore.MediaColumns.SIZE, file.length());
contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(path);
Cursor cursor = context.getContentResolver().query(uri, null, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
String id = cursor.getString(0);
contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
context.getContentResolver().update(uri, contentValues, MediaStore.MediaColumns.DATA + "=?", new String[]{path});
Uri newuri = ContentUris.withAppendedId(uri, Long.valueOf(id));
try {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newuri);
Toast.makeText(context, "Set as Ringtone Successfully.", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
t.printStackTrace();
}
cursor.close();
}
}
If the accepted answer is not working then use this:
MediaStore.Audio.Media.INTERNAL_CONTENT_URI
instead of this:
MediaStore.Audio.Media.getContentUriForPath()
while inserting values into the database.
For example :
// Defining ringtone.....
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Sonify");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
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);
// Setting ringtone....
getContentResolver().delete(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,MediaStore.Audio.Media.TITLE + " = \"Sonify\"",null);
// To avoid duplicate inserts
Uri ringUri = getContentResolver().insert(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM, ringUri);
Dont forgot to add
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Use this function to set Ringtone
private void setAsRingtone(String musicId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(this)) {
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.parseLong(musicId));
RingtoneManager.setActualDefaultRingtoneUri(
this,
RingtoneManager.TYPE_RINGTONE,
uri
);
Toast.makeText(this, "Ring set successfully", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
Music Id can be obtained from Cursor. Hope you know it, or
Check it here
That works for me even in android S
,hope its help to you in set ringtone in android programmatically
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, uri);
I found this code from the Media application from Android.
Settings.System.putString(resolver,
Settings.System.RINGTONE, ringUri.toString());
this works form my.