3
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;
}
}

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

4

6 回答 6

9

在您想听音乐的活动中使用它

mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
于 2013-08-09T05:10:22.533 回答
4
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();
于 2013-08-09T04:53:32.400 回答
1

如果是因为您只是在 onCreate() 上加载声音并在触摸时播放它!试试soundPlay.play()onCreate 吧!

于 2013-08-09T05:02:10.123 回答
1

您可以在可运行文件中播放声音并将其发布到 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);
                }
            }
        });
于 2013-08-09T05:22:33.667 回答
0

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

于 2013-08-09T05:52:00.540 回答
0

如果您的活动名称是MainActivity

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

将其放在 onCreate 方法中

于 2019-12-23T12:04:12.120 回答