gpt4 book ai didi

java - 将一段声音保存为铃声

转载 作者:行者123 更新时间:2023-11-30 02:05:20 26 4
gpt4 key购买 nike

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

谢谢!!

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

最佳答案

对于遇到此问题的任何其他人,我已经弄明白了。就是这条线。

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

如果有人碰巧知道这是为什么,我会很想知道。谢谢!

关于java - 将一段声音保存为铃声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com