添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm new to Kotlin and am trying to make a simple AudioManager (wrapping MediaPlayer).

I want the class to play the audio.

Here is my class:

package com.example.myappname
import android.media.MediaPlayer
interface AudioManagerInput {
    fun startSound()
    fun stopSound()
class AudioManager: AudioManagerInput {
    // Instance variables
    private var mediaPlayer: MediaPlayer? = null
    // AudioManagerInput methods
    override fun startSound() {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer()
            mediaPlayer?.setDataSource("R.raw.songone") // ???
        mediaPlayer?.start()
    override fun stopSound() {
        mediaPlayer?.stop()

I'm having issues setting the song.

I'm looking to load a local file R.raw.songone which is a .wav file sitting in res/raw.

How can I get a String to it's path?

I've scoured tutorials which hold other solutions to using MediaPlayer but have had issues with not knowing what to import, not being able to call create, or context not being found (whatever that is).

Modify class or it's method signature like this:

class AudioManager(private val context: Context): AudioManagerInput

Now we can pass context to MediaPlayer:

override fun startSound() {
    if (mediaPlayer == null) {
        mediaPlayer = MediaPlayer.create(context, R.raw.yourSound);
    mediaPlayer?.start()

To init your AudioManager from an Activity:

var audioManager = AudioManager(this)

To manually access raw files: Read/write from res/raw by name.

How do I pass in the context from the calling class? class MainActivity : AppCompatActivity() – Chris Allinson Oct 6, 2019 at 4:44 I have created like in this way and my object is cleared a few seconds with GC, keeping object static with companion object { var mediaPlayer: MediaPlayer? = null } is solved. fyi.. – ayciceksamet May 24, 2020 at 14:06 Not a good approach, I don't know how you are using the object, judging from your comment I would rather move it to a foreground service. – Taseer May 24, 2020 at 17:28

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.