2013-04-30 43 views
0

在我的活动中,有一个定时器每秒发送一条消息给一个处理程序,它会改变图像。只要定时器中断MediaPlayer

MediaPlayer.create(this, R.raw.voice).start(); 

在一个XPERIA弧(4.0.4的Android)的声音不完全播放和:

每次用户点击的声音被使用此代码在活动的onClickListner功能发挥的图像计时器触发它停止。如果我禁用了计时器,那就没有问题了。

在HTC Legend(Android 2.2)上没有问题。声音完全播放。

我找不出这个问题。

public class ActivityTest extends Activity implements View.OnClickListener, ViewSwitcher.ViewFactory 
{ 

    ImageSwitcher switcher; 

    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test_listen); 

     switcher = (ImageSwitcher) findViewById(R.id.imageSwitcher); 
     switcher.setFactory(this); 
     switcher.setOnClickListener(this); 

     final Handler handler = new Handler() 
     { 
      @Override 
      public void handleMessage(Message msg) 
      { 
       switcher.setImageDrawable(getResources().getDrawable(R.drawable.image)); 
       // if this line is commented it works fine 
      } 
     }; 

     new Timer().scheduleAtFixedRate(new TimerTask() { 
      @Override 
      public void run() 
      { 
       handler.sendEmptyMessage(0); 
      } 
     }, 0, 1000); 
    } 

    @Override 
    public void onClick(View view) 
    { 
     MediaPlayer.create(this, R.raw.voice).start(); 
    } 


    @Override 
    public View makeView() 
    { 
     ImageView image = new ImageView(this); 
     image.setScaleType(ImageView.ScaleType.FIT_CENTER); 
     image.setLayoutParams(new ImageSwitcher.LayoutParams(ImageSwitcher.LayoutParams.FILL_PARENT, ImageSwitcher.LayoutParams.FILL_PARENT)); 
     return image; 
    } 
} 

解决方案-------------------------------------

我将MediaPlayer的声明移到了课堂上,并解决了问题。

MediaPlayer mp; 
    @Override 
    public void onClick(View view) 
    { 
     mp =MediaPlayer.create(this, R.raw.voice); 
     mp.start(); 
    } 

我不知道为什么以前的代码工作在2.2但不是4.无论如何它的工作。

回答

1

因为它的短暂声音你玩我建议一个soundpool。 Soundpool剪辑保存在内存中以便快速访问,因为它们很小。我假设你演奏的声音很短。在的onCreate这样做是为了预载:

// Load the sound 
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); 
soundID= soundPool.load(this, R.raw.voice, 1); 

    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { 
     @Override 
     public void onLoadComplete(SoundPool soundPool, int sampleId, 
       int status) { 
      loaded = true; 
     } 
    }); 

然后在onclick方法(当用户点击图片)这样做:

AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); 
      float actualVolume = (float) audioManager 
        .getStreamVolume(AudioManager.STREAM_MUSIC); 
      float maxVolume = (float) audioManager 
        .getStreamMaxVolume(AudioManager.STREAM_MUSIC); 
      float volume = actualVolume/maxVolume; 

      if (loaded) { 
       soundPool.play(soundID, volume, volume, 1, 0, 1f); 
} 

其中的Soundpool声明为实例变量私有的Soundpool的Soundpool什么类似。尝试一下,让我知道发生了什么。

+0

SoundPool不播放任何内容。这是mp3。 Soundpool支持mp3吗?它在播放时返回0。 – Ali 2013-04-30 20:36:08

+0

是soundpools播放mp3的我刚刚更新了我的答案。 – j2emanue 2013-04-30 21:28:45