我正在制作一个消防应用程序,允许我从列表视图中选择不同的音色,如果愿意,可以将它们添加到队列中,然后按下按下播放按钮时按照选择的顺序播放它们。我已经看过有关使用媒体播放器阵列的一些内容,但不确定如何将声音文件或参考ID添加到数组中,以便可以从索引0中的第一个选定声音开始播放它们到最后一个最后一个索引。任何帮助表示赞赏。
答案 0 :(得分:1)
这样的东西?
//
import android.media.AudioManager;
import android.media.SoundPool;
import android.app.Activity;
//
import java.util.HashMap;
//
import us.kristjansson.android.R;
public class CxMediaPlayer
{
private SoundPool mShortPlayer= null;
private HashMap mSounds = new HashMap();
// Constructor
public CxMediaPlayer( Activity pContext )
{
// setup Soundpool
this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
// 0-9 Buttons
mSounds.put( R.raw.button_1, this.mShortPlayer.load(pContext, R.raw.button_1, 1) );
mSounds.put( R.raw.button_2, this.mShortPlayer.load(pContext, R.raw.button_2, 1) );
mSounds.put( R.raw.button_3, this.mShortPlayer.load(pContext, R.raw.button_3, 1) );
mSounds.put( R.raw.button_4, this.mShortPlayer.load(pContext, R.raw.button_4, 1) );
mSounds.put( R.raw.button_5, this.mShortPlayer.load(pContext, R.raw.button_5, 1) );
mSounds.put( R.raw.button_6, this.mShortPlayer.load(pContext, R.raw.button_6, 1) );
mSounds.put( R.raw.button_7, this.mShortPlayer.load(pContext, R.raw.button_7, 1) );
// Others
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.correct_answer, 1) );
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.wrong_answer, 1) );
}
// Plays the passed preloaded resource
public void playShortResource( int piResource )
{
int iSoundId = mSounds.get( piResource );
this.mShortPlayer.play( iSoundId, 0.99f, 0.99f, 0, 0, 1 );
}
// Cleanup
public void Release()
{
// Cleanup
this.mShortPlayer.release();
this.mShortPlayer = null;
}
}
然后,您在Activity中需要的只是启动播放器类并调用 当你需要播放声音时播放快照资源。您的资源应该在 res / raw目录。
// The media player – OnCreate
mxMediaPlayer = new CxMediaPlayer( this );
// Play the desired sound – OnClick
mxMediaPlayer.playShortResource( R.raw.button_1 );
// Make sure to release resources when done – OnDestroy
mxMediaPlayer.Release();
并在您的情况下将它们添加到数组,然后循环播放
toPlay.Add( R.raw.button_1 )
toPlay.Add( R.raw.button_3 )
toPlay.Add( R.raw.button_7 );
Foreach( item in toPlay list )
mxMediaPlayer.playShortResource( item )