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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.