3
0

More than 5 years have passed since last update.

音ゲー作成までの道のり3

Last updated at Posted at 2019-08-30

前回までのあらすじと今回の成果

前回までは、メトロノームを作成し端末を左右に振れば音が出る、というところまで作成できた。
そこから今回はBGMを付けようと思い簡易的なミュージックプレイヤーを作成したので下記にレイアウトとソースコードを記載する。

レイアウト

キャプチャM.PNG

activiti_main.xml
    <SeekBar
        android:id="@+id/Time_Seek"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="75dp"
        android:layout_marginLeft="75dp"
        android:layout_marginEnd="75dp"
        android:layout_marginRight="75dp"
        android:layout_marginBottom="250dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/Time_text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="75dp"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="4dp"
        android:text="0:00"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/Time_Seek" />

    <TextView
        android:id="@+id/Time_text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="75dp"
        android:layout_marginRight="75dp"
        android:text="- 0:00"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/Time_Seek" />

    <SeekBar
        android:id="@+id/Volume_seek"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="75dp"
        android:layout_marginLeft="75dp"
        android:layout_marginEnd="75dp"
        android:layout_marginRight="75dp"
        android:layout_marginBottom="50dp"
        android:max="100"
        android:progress="50"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="38dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/Volume_seek"
        app:srcCompat="@drawable/sound" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginBottom="38dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/Volume_seek"
        app:srcCompat="@drawable/sound2" />

    <Button
        android:id="@+id/Music_button"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginStart="150dp"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="150dp"
        android:layout_marginRight="150dp"
        android:layout_marginBottom="50dp"
        android:background="@drawable/play"
        app:layout_constraintBottom_toTopOf="@+id/Volume_seek"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/Time_Seek" />

    <Button
        android:id="@+id/beat1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="75dp"
        android:layout_marginLeft="75dp"
        android:layout_marginEnd="75dp"
        android:layout_marginRight="75dp"
        android:layout_marginBottom="75dp"
        app:layout_constraintBottom_toTopOf="@+id/Time_Seek"
        app:layout_constraintEnd_toStartOf="@+id/beat2"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/beat2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="75dp"
        android:layout_marginLeft="75dp"
        android:layout_marginEnd="75dp"
        android:layout_marginRight="75dp"
        android:layout_marginBottom="75dp"
        app:layout_constraintBottom_toTopOf="@+id/Time_Seek"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/beat1" />

ソースコード

MainActivity.java
public class MainActivity extends AppCompatActivity {

    private MediaPlayer mp;
    private Button m_but,b_but1,b_but2;
    private SeekBar v_bar,m_bar;
    private TextView s_text,e_text;
    private int m_time;

    SoundPool soundPool;
    int mp3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        m_but = findViewById(R.id.Music_button);
        b_but1 = findViewById(R.id.beat1);
        b_but2 = findViewById(R.id.beat2);
        s_text = findViewById(R.id.Time_text1);
        e_text = findViewById(R.id.Time_text2);

        //曲の読み込み
        mp = MediaPlayer.create(this,R.raw.impact);
        mp.setLooping(true);
        mp.setVolume(1f,1f);
        m_time = mp.getDuration();

        //効果音付けるのに必要なやつ
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        } else {
            AudioAttributes attr = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
            soundPool = new SoundPool.Builder()
                    .setAudioAttributes(attr)
                    .setMaxStreams(5)
                    .build();
        }

        mp3 = soundPool.load(this, R.raw.pop, 1);

        m_bar = findViewById(R.id.Time_Seek);
        m_bar.setMax(m_time);
        m_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mp.seekTo(progress);
                    m_bar.setProgress(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        v_bar = findViewById(R.id.Volume_seek);
        v_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float v_num = progress / 100f;
                mp.setVolume(v_num,v_num);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //再生ボタン制御
        m_but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mp.isPlaying()){
                    mp.pause();
                    m_but.setBackgroundResource(R.drawable.play);
                }
                else {
                    mp.start();
                    m_but.setBackgroundResource(R.drawable.stop);
                }
            }
        });

        b_but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                soundPool.play(mp3, 2, 2, 0, 0, 1f);
            }
        });

        b_but2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                soundPool.play(mp3, 2, 2, 0, 0, 1f);
            }
        });


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mp !=null){
                    try {
                        Message msg = new Message();
                        msg.what = mp.getCurrentPosition();
                        handler .sendMessage(msg);
                        Thread.sleep(1000);
                    } catch (InterruptedException e){}
                }
            }
        }).start();
    }

    private Handler handler =new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int currentPosition = msg.what;

            // 再生位置を更新
            m_bar.setProgress(currentPosition);

            // 経過時間ラベル更新
            String elapsedTime = createTimeLabel(currentPosition);
            s_text.setText(elapsedTime);

            // 残り時間ラベル更新
            String remainingTime = "- " + createTimeLabel(m_time-currentPosition);
            e_text.setText(remainingTime);

            return true;
        }
    });

    public String createTimeLabel(int time) {
        String timeLabel = "";
        int min = time / 1000 / 60;
        int sec = time / 1000 % 60;

        timeLabel = min + ":";
        if (sec < 10) timeLabel += "0";
        timeLabel += sec;

        return timeLabel;
    }
}

今回の頑張り

前回から少し日が開いてしまいましたが、簡易的なミュージックプレイヤーを作成するのが結構難しく、音楽が流れなかったり、流れたのはいいが一時停止すると音楽が再生されなかったり、音楽を停止すると共にアプリも停止するし...
結構難しかったってのが感想なんですが、じゃあ何が原因だったかというと、停止した際にmpの中身をnullにしていたので再び再生する際に何かしらのエラーを起こしていたのだと私は考えています。間違ていたらすいませんm(_ _)m
ちなみに、レイアウトにある2つの何も書いてないボタンはなんぞやと思われる方が多いと思いますが、これを押すと効果音が鳴ります!...
えっ?他にはって?



以上です。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0