本文介绍了Kotlin MediaPlayer的简单用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Kotlin的新手,正在尝试制作一个简单的AudioManager(包装MediaPlayer).

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

我想让班级播放音频.

这是我的课程:

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.

我要加载本地文件 R.raw.songone ,它是位于 res/raw 中的.wav文件.

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?

我已经仔细研究了使用MediaPlayer的其他解决方案的教程,但是遇到了以下问题:不知道要导入的内容,无法调用 create context 被发现(无论是什么).

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

推荐答案

将上下文导入AudioManager:

Import Context into AudioManager:

import android.content.Context

修改类或其方法签名,如下所示:

Modify class or it's method signature like this:

class AudioManager(private val context: Context): AudioManagerInput

现在我们可以将上下文传递给 MediaPlayer :

Now we can pass context to MediaPlayer:

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

要通过活动"初始化AudioManager,请执行以下操作:

To init your AudioManager from an Activity:

var audioManager = AudioManager(this)

要手动访问 raw 文件:按名称从res/raw读取/写入.

这篇关于Kotlin MediaPlayer的简单用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 23:01