简体   繁体   中英

save audio file using MediaStore API

I'm trying to create the URI but my app crached.this is my code.

ContentValues values1 = new ContentValues(1);
        values1.put(MediaStore.Audio.Media.DISPLAY_NAME, "My Song.mp3");
        ContentResolver resolver = getApplicationContext().getContentResolver();
        audiouri = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values1);

And this is the error that i got.

2021-09-20 00:22:22.963 24197-24197/com.example.voicetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.voicetest, PID: 24197
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(int)' on a null object reference
    at android.os.Parcel.createException(Parcel.java:1956)
    at android.os.Parcel.readException(Parcel.java:1918)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
    at android.content.ContentProviderProxy.insert(ContentProviderNative.java:476)
    at android.content.ContentResolver.insert(ContentResolver.java:1587)
    at com.example.voicetest.MainActivity$1.onClick(MainActivity.java:148)
    at android.view.View.performClick(View.java:7044)
    at android.view.View.performClickInternal(View.java:7017)
    at android.view.View.access$3200(View.java:784)
    at android.view.View$PerformClick.run(View.java:26596)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6819)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)

UPDATE

I added this code and it's work fine, but getContentResolver().insert() return null

   File directory = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
   values.put(MediaStore.Audio.AudioColumns.DATA, "${directory}${song?.title}");
                File directory = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
            values.put(MediaStore.Audio.AudioColumns.DATA, "${directory}${song?.title}");

I added this code and it's work fine, but getContentResolver().insert() return null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM