Android - 如何将歌曲设置为铃声或来自原始文件夹的通知?

时间:2014-03-27 22:43:51

标签: android listview audio ringtone

我有一个带有声音项目的列表视图。我需要,当一个项目长按es时,将其设置为铃声或通知我的应用程序的原始声音。我怎样才能做到这一点?感谢

2 个答案:

答案 0 :(得分:0)

在这里回答我的其他帖子......

Set ringtone from res/raw folder

您无法从资源设置铃声。

RingtoneManager.setActualDefaultRingtoneUri期望设备中的铃声文件和Uri应来自内容解析器。

    File ring = new File("pathOfYourFile");
     Uri path = MediaStore.Audio.Media.getContentUriForPath(ring.getAbsolutePath());

RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(),RingtoneManager.TYPE_RINGTONE,path);

还要确保添加权限

答案 1 :(得分:0)

试试这段代码

 String name = "your_raw_audio_name";

 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) {

    }

更多细节请查看此link