To select an audio file using Intent , I am using this function :-
fun selectAudioFromStorage() {
val pictureActionIntent = Intent(Intent.ACTION_GET_CONT
I solved it. Simply call this getPathFromURI method and it will return the file path
object RealPathHelper {
private const val BUFFER_SIZE = 1024 * 2
@TargetApi(Build.VERSION_CODES.O)
fun getPathFromURI(
context: Context,
contentUri: Uri,
fileNamePrefix: String,
defaultFileExtension: String
): String? {
val uriPath: String = contentUri.path ?: return null
val fileName: String = MediaFileHelper.getFileNameWithExtension(uriPath)
if (fileName.isNotBlank()) {
val destFile =
createOutputFile(context, contentUri, fileNamePrefix, defaultFileExtension)
copyUriToFile(context, contentUri, destFile)
return destFile.absolutePath
}
return null
}
private fun createOutputFile(
context: Context,
contentUri: Uri,
fileNamePrefix: String,
defaultFileExtension: String
): File {
var count = 0
var file: File
val uriPath: String? = contentUri.path
val fileExtension = if (uriPath == null) defaultFileExtension
else MediaFileHelper.getFileExtension(uriPath)
do {
count++
val mFileName = "$fileNamePrefix${StringHelper.getUniqueId()}$count$fileExtension"
val newFilePath =
"${context.getExternalFilesDir(null)?.absolutePath}${context.getString(R.string.audio_select_directory)}/$mFileName"
file = File(newFilePath)
} while (file.exists() && !file.isDirectory)
return file
}
private fun copyUriToFile(context: Context, srcUri: Uri, dstFile: File) {
try {
val inputStream = context.contentResolver.openInputStream(srcUri) ?: return
val outputStream = FileOutputStream(dstFile)
inputStream.copyTo(outputStream, BUFFER_SIZE)
inputStream.close()
outputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}