我的活动开始时如何播放声音

时间:2013-08-09 04:50:45

标签: android

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    View view = findViewById(R.id.textView1);
    view.setOnTouchListener(this);

    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) {
            loaded = true;
        }
    });
    soundID = soundPool.load(this, R.raw.dog_bark, 1);

 }
;
@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {

        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);
        }
    }
    return false;
}
}

我试过这种方式,但声音正在触摸事件中播放。我希望在我的活动开始时自动播放声音。但它应该在循环完成后停止并在触摸事件上再次启动。请帮忙。

6 个答案:

答案 0 :(得分:8)

在您想听音乐的活动中使用此功能

mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();

答案 1 :(得分:5)

public class CommonMethod {
public static MediaPlayer player;
public static void SoundPlayer(Context ctx,int raw_id){
        player = MediaPlayer.create(ctx, raw_id);
        player.setLooping(false); // Set looping
        player.setVolume(100, 100);

        //player.release();
         player.start();
    }
}

//you can use this method for stopping the player.
CommonMethod.player.stop();

答案 2 :(得分:1)

如果是因为你只是在onCreate()上加载声音并在触摸时播放它! 请改用onCreate中的soundPlay.play()

答案 3 :(得分:1)

你可以在runnable中播放声音并在onCreate方法中发布。

View view = findViewById(R.id.textView1);
view.post(new Runnable() {

            @Override
            public void run() {
                if (loaded) {
                    soundPool.play(soundID, volume, volume, 1, 0, 1f);
                }
            }
        });

答案 4 :(得分:0)

将onTouch()方法的代码放入Activity的OnStart()方法中,以便在活动开始时播放声音。

答案 5 :(得分:0)

如果您的活动名称是MainActivity

MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.sound);
play.start();

将其放在onCreate方法中