Android: mediaplayer create

前端 未结 2 1123
野性不改
野性不改 2020-12-04 00:19

I have this code:

package com.example.pr;

import android.media.MediaPlayer;

public class Audio{

    MediaPlayer mp;

    public void playClick(){
                 


        
相关标签:
2条回答
  • 2020-12-04 00:45

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

    try:

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

    in your Activity:

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

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

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

    0 讨论(0)
  • 2020-12-04 01:04
    public class Audio{
    
        MediaPlayer mp;
    Context context;
    
         public Audio(Context ct){
         this.context = ct;
    }
        public void playClick(){
            mp = MediaPlayer.create(context, R.raw.click);  
            mp.prepare();
            mp.start();
        }
    

    From your Activity:

    Audio audio = new Audio(YourActivity.getApplicationContext());
    audio.playClick();
    
    0 讨论(0)
提交回复
热议问题