安卓:媒体播放器创建媒体播放器

2023-09-04 10:44:54 作者:残留旳爱ゝ余温散尽

我有这个code:

package com.example.pr;

import android.media.MediaPlayer;

public class Audio{

    MediaPlayer mp;

    public void playClick(){
        mp = MediaPlayer.create(Audio.this, R.raw.click);  
        mp.start();
    }
}

我在创造与此消息的方法来创建(背景下,INT)在类型的MediaPlayer不适用的参数(音频,INT)的错误

I have an error in "create" with this message "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (Audio, int)"

为什么?

推荐答案

MediaPlayer.create()需要的上下文的作为第一个参数。通过当前的活动的,它应该工作。

MediaPlayer.create() needs a Context as first parameter. Pass in the current Activity and it should work.

尝试:

public void playClick(Context context){
    mp = MediaPlayer.create(context, R.raw.click);  
    mp.start();
}

在你的活动:

audio = new Audio();
...
audio.playClick(this);

但不要忘记呼吁MediaPlayer的情况下,一旦释放的声音已经完成,否则你会得到一个异常。

but don't forget to call release on the MediaPlayer instance once the sound has finished, or you'll get an exception.

不过,对于打短点击使用的的Soundpool 的可能会更好呢。

However, for playing short clicks using a SoundPool might be better anyway.

 
精彩推荐