Accessing Assets

Recall that your sound files are stored in your app’s assets. Before you access those files to play the audio, let’s discuss a bit more about how assets work.

Your Sound object has an asset file path defined on it. Asset file paths will not work if you try to open them with a File; you must use them with an AssetManager:

    val assetPath = sound.assetPath

    val assetManager = context.assets

    val soundData = assetManager.open(assetPath)

This gives you a standard InputStream for the data, which you can use like any other InputStream in Kotlin.

Some APIs require FileDescriptors instead. This is what you will use with SoundPool. If you need that, you can call AssetManager.openFd(String) instead:

 val assetPath = sound.assetPath ...

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.