保存声音作为铃声

时间:2015-06-10 03:31:06

标签: java android audio media ringtone

我正在尝试将.wav文件设置为Android设备上的铃声。下面的代码能够创建目录和声音文件,但似乎有问题实际上将文件设置为铃声,更不用说选定的铃声了。方法结束后,我转到设备上的铃声,所选铃声默认为"无"。知道这里发生了什么吗?我在清单中使用WRITE_EXTERNAL_STORAGE权限。另外,声音咬合的格式对我来说并不重要,我不介意转换任何需要转换的东西。

谢谢!

private String saveAs(String fileName) {
    int resSound = getContext().getResources().getIdentifier(fileName, "raw", getContext().getPackageName());

    // Resolve save path and ensure we can read and write to it
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/audio/ringtones/";
    File dir = new File(path);
    fileName += ".wav";

    if (!dir.exists()) {
        dir.mkdirs();
    }

    if(!dir.canRead() || !dir.canWrite()) {
        return "Unable to save ringtone.";
    }

    // Load the audio into a buffer
    byte[] buffer;
    InputStream fIn = this.context.getBaseContext().getResources().openRawResource(resSound);
    int size;

    try {
        size = fIn.available();
        buffer = new byte[size];
        fIn.read(buffer);
        fIn.close();
    }
    catch (IOException e) {
        return "Error opening sound file";
    }


    File file = new File(dir, fileName);
    FileOutputStream save;
    try {
        save = new FileOutputStream(file);
        save.write(buffer);
        save.flush();
        save.close();
    }
    catch (FileNotFoundException e) {
        return "Error loading sound file.";
    }
    catch (IOException e) {
        return "Unable to save ringtone.";
    }

    // Register the sound byte with the OS and set its properties
    this.context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path + fileName)));

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, getSoundTitle(fileName));
    values.put(MediaStore.MediaColumns.SIZE, size);
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
    values.put(MediaStore.Audio.Media.ARTIST, "Sound Clip");
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

    //Insert it into the database
    Uri uri = this.context.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath()), values);
    RingtoneManager.setActualDefaultRingtoneUri(this.context, RingtoneManager.TYPE_RINGTONE, uri);

    return "Successfully set ringtone.";
}

1 个答案:

答案 0 :(得分:1)

对于遇到这种情况的其他人,我想通了。就是这条线。

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

如果有人碰巧知道为什么会这样,我会非常有兴趣知道。谢谢!