2014-02-22 143 views
0

我试图做一个扩展Mediaplayer的类,当我播放声音时我想在调用声音的活动中触发一个事件处理程序。音频没有播放

我的活动:

SoundPlayer soundPlayer = new SoundPlayer(BookInterface.this); 
soundPlayer.playSound(this, R.raw.vroom); 

这是声音播放类:

public class SoundPlayer extends MediaPlayer{ 

    BookInterface ownerActivity; 

    public SoundPlayer(BookInterface act){ 
     ownerActivity = act; 
    } 

    public void playSound(Context context, int resId){ 
     Log.d("Debug", "playSound is called"); 
     MediaPlayer mp = new MediaPlayer(); 
     try { 
      mp = MediaPlayer.create(context, resId); 
      mp.start(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      Log.d("Debug","Exception" + e); 
      e.printStackTrace(); 
     } 

     mp.setOnCompletionListener(new OnCompletionListener() { 

      @Override 
      public void onCompletion(MediaPlayer mp) { 
       Log.d("Debug", "playSound.onCompletion is called"); 
       mp.stop(); 
       mp.release(); 
       ownerActivity.eventHandler(); 
      } 
     });  
    } 
} 

为什么心不是声音播放? 我在做什么错?

BR

+0

尝试注册使用setOnErrorListener错误监听器。 – Merlevede

+0

@Merlevede:从那里一无所获。似乎声音在播放,因为我可以改变soundvolume而不是phonevolume。但正如我所说,没有错误。 –

回答

0

为什么你宣布你MediaPlayerplaySound方法?
我认为当playSound方法执行完成您的MediaPlayer从内存中清除,试图声明MediaPlayer的是这样的类变量:

public class SoundPlayer extends MediaPlayer{ 

    BookInterface ownerActivity; 
    private MediaPlayer mp; 

    public SoundPlayer(BookInterface act){ 
     ownerActivity = act; 
    } 

    public void playSound(Context context, int resId){ 
     Log.d("Debug", "playSound is called"); 
     try { 
      mp = MediaPlayer.create(context, resId); 

      mp.setOnCompletionListener(new OnCompletionListener() { 

       @Override 
       public void onCompletion(MediaPlayer mp) { 
        Log.d("Debug", "playSound.onCompletion is called"); 
        mp.stop(); 
        mp.release(); 
        ownerActivity.eventHandler(); 
       } 
      }); 

      mp.start(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      Log.d("Debug","Exception" + e); 
      e.printStackTrace(); 
     }  
    } 
}