There is no definite solution to your problem AFAIK, but I can share my thoughts on it.
From documentation:
If your app is running in the background on a device running Android 9... it cannot access the microphone
Furthermore since Android 9 you can force an app to use microphone (and other operations) only in foreground:
~$ appops set com.discord RECORD_AUDIO foreground
Both of the above are applicable only if the app is not running a foreground service i.e. not showing a persistent notification.
In case of older Android version or if the app is running a foreground service you can try to make use of some automation apps to revoke RECORD_AUDIO
permission and/or operation as soon as screen is locked:
~$ pm revoke org.lineageos.recorder android.permission.RECORD_AUDIO
~$ appops set com.discord RECORD_AUDIO ignore
And do the inverse when screen is unlocked.
However Android framework mostly kills/restarts the app/service when a permission is revoked. Or the app may continue using the previous state of permission unless it's manually restarted. So the approach is not reliable but may work for some apps under certain circumstances.
For example to stop apps on screen lock, or to auto-disable microphone after some time.
Stock Android doesn't provide any such feature to auto-disable or disable mic from lock screen, though a custom ROM developer or OEM may provide e.g. a "Turn Mic Off" tile. Some ROMs add "Kill app" button to notification (on long press). But that may require unlocking the screen. Again you can automate to kill the app on screen lock. But some apps may also start a service on broadcast events.