[JAVA] The road to creating a music game 3

Synopsis up to the last time and the results of this time

Until the last time, I was able to create a metronome and shake the terminal left and right to make a sound. From there, I created a simple music player with the intention of adding BGM, so I will describe the layout and source code below.

Layout

キャプチャ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" />

Source code

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);

        //Loading a song
        mp = MediaPlayer.create(this,R.raw.impact);
        mp.setLooping(true);
        mp.setVolume(1f,1f);
        m_time = mp.getDuration();

        //The one you need to add sound effects
        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) {

            }
        });

        //Play button control
        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;

            //Update playback position
            m_bar.setProgress(currentPosition);

            //Elapsed time label update
            String elapsedTime = createTimeLabel(currentPosition);
            s_text.setText(elapsedTime);

            //Remaining time label update
            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;
    }
}

Good luck this time

It's been a while since the last time, but it's quite difficult to create a simple music player, the music doesn't play, it's good to play, but when it's paused, the music doesn't play, or the music stops. At the same time, the app will stop ... I think that it was quite difficult, but what was the cause was that the contents of mp were null when it stopped, so I thought that it caused some error when playing it again. I am. I'm sorry if I made a mistake m (_ _) m By the way, many people think that the two blank buttons on the layout are strange, but when you press them, you will hear a sound effect! ... eh? What else? ・ ・ ・ that's all.

Recommended Posts

The road to creating a music game 2
The road to creating a music game 3
The road to creating a music game 1
The road to creating a Web service (Part 1)
The road from JavaScript to Java
I tried to illuminate the Christmas tree in a life game
The road to Web service creation (Part 2)
Creating a Servlet in the Liberty environment
A memorandum to clean up the code Ruby
The road to Japaneseizing Rails devise error messages
Make a margin to the left of the TextField
Set the time of LocalDateTime to a specific time
Try to make a music player using Basic Player
3. Create a database to access from the web module
A brief introduction to terasoluna5, see the text below
How to run the SpringBoot app as a service
I tried to decorate the simple calendar a little
Creating a Cee-lo game with Ruby 4th Creating a game progress process
Things to watch out for when creating a framework
How to make a mod for Slay the Spire
I want to add a delete function to the comment function
Creating a local repository
Road to REPL (?) Creation (3)
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
Road to REPL (?) Creation (1)
Road to REPL (?) Creation (2)
[Rails] Processing after adding a column to the devise table
How to take a screenshot with the Android Studio emulator
SDWebImage: How to clear the cache for a particular UIImageView
[Beginner] Try to make a simple RPG game with Java ①
How to create a form to select a date from the calendar
[IOS] What you need to know before creating a widget
I want to call a method and count the number
I want to create a form to select the [Rails] category
Create a method to return the tax rate in Java
[Ruby] How to retrieve the contents of a double hash
A validation error occurred when saving to the intermediate table.
How to add the same Indexes in a nested array
I want to give a class name to the select attribute
Add a shadow to the Swift Button (and also the circle)
A memorandum to reach the itchy place for Java Gold
[ruby] Creating a program that responds only to specific conditions
[jsoup] How to get the full amount of a document