简体   繁体   中英

Kotlin MediaPlayer simple usage

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).

Import Context into AudioManager:

import android.content.Context

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 .

You can read all about MediaPlayer this .

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