Home>
Thing I want to do

When you tap the start button in Kotlin, you will hear a sound
I want to make an app for practice that stops the sound when I tap the stop button.

I know I use MediaPlayer to make a sound,
I don't know where to put the MediaPlayer code in the activity.
If i try to enter it in Mainactivity.kt, the audio will open and play on your computer.
The app could not be opened.

Activity to write code or
If i have any good methods or sites other than this code, I would appreciate it if you could teach me.

Code
package com.example.oto
import android.content.Context
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main. *

class MainActivity: AppCompatActivity () {
    private val musicManager: MusicManager = MusicManager (this @ MainActivity)
    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)
        // Button for start music
        val buttonStart: Button = findViewById (R.id.start_music)
        // Resister listener
        buttonStart.setOnClickListener {
            musicManager.startMusic ()
        }
        // Button for stop music
        val buttonStop: Button = findViewById (R.id.stop_music)
        // Resister listener
        buttonStop.setOnClickListener {
            musicManager.stopMusic ()
        }
    }
}

class MusicManager (context: Context) {
    private lateinit var mediaPlayer: MediaPlayer
    private val myContext: Context = context
    fun startMusic () {
        mediaPlayer = MediaPlayer.create (myContext, R.raw.test)
        mediaPlayer.isLooping = true
        mediaPlayer.start ()
    }fun stopMusic () {
        mediaPlayer.stop ()
        mediaPlayer.reset ()
        mediaPlayer.release ()
    }
}
Supplementary information

androidstudio4.1

It will be an addition to the comment
2020-12-14 19: 51: 11.901 19828-19828/com.example.oto E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.oto, PID: 19828
    java.lang.RuntimeException: Unable to start activity ComponentInfo {com.example.oto/com.example.oto.MainActivity}: java.lang.NullPointerException: findViewById (R.id.start_music) must not be null
        at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
        at android.app.ActivityThread $H.handleMessage (ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage (Handler.java:106)
        at android.os.Looper.loop (Looper.java:193)
        at android.app.ActivityThread.main (ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke (Native Method)
        at com.android.internal.os.RuntimeInit $MethodAndArgsCaller.run (RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: findViewById (R.id.start_music) must not be null
        at com.example.oto.MainActivity.onCreate (MainActivity.kt:19)
        at android.app.Activity.performCreate (Activity.java:7136)
        at android.app.Activity.performCreate (Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
        at android.app.ActivityThread $H.handleMessage (ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage (Handler.java:106)
        at android.os.Looper.loop (Looper.java:193)
        at android.app.ActivityThread.main (ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke (Native Method)
        at com.android.internal.os.RuntimeInit $MethodAndArgsCaller.run (RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:858)
Photo

♯ Addition to comment activity_main

<? xml version = "1.0" encoding = "utf-8"?><Button
        android: id = "@ + id/button"
        android: layout_width = "wrap_content"
        android: layout_height = "wrap_content"
        android: text = "@ string/start"
        tools: layout_editor_absoluteX = "143dp"
        tools: layout_editor_absoluteY = "119dp" /><Button
        android: id = "@ + id/button2"
        android: layout_width = "wrap_content"
        android: layout_height = "wrap_content"
        android: text = "@ string/stop"
        tools: layout_editor_absoluteX = "138dp"
        tools: layout_editor_absoluteY = "363dp" /></androidx.constraintlayout.widget.ConstraintLayout>

♯Addition to comments: I'm sorry many times.

2020-12-14 21: 11: 28.702 21871-21896/com.example.oto E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type = 5, ret = -1
2020-12-14 21: 11: 28.928 21871-21896/com.example.oto D/EGL_emulation: eglMakeCurrent: 0xe7e90700: ver 2 0 (tinfo 0xefb625c0)
2020-12-14 21: 11: 37.371 21871-21871/com.example.oto D/AndroidRuntime: Shutting down VM
2020-12-14 21: 11: 37.373 21871-21871/com.example.oto E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.oto, PID: 21871
    kotlin.UninitializedPropertyAccessException: lateinit property mediaPlayer has not been initialized
        at com.example.oto.MainActivity.stopMusic (MainActivity.kt:42)
        at com.example.oto.MainActivity $onCreate $2.onClick (MainActivity.kt: 31)
        at android.view.View.performClick (View.java:6597)
        at com.google.android.material.button.MaterialButton.performClick (MaterialButton.java:992)
        at android.view.View.performClickInternal (View.java:6574)
        at android.view.View.access $3100 (View.java:778)
        at android.view.View $PerformClick.run (View.java:25885)
        at android.os.Handler.handleCallback (Handler.java:873)
        at android.os.Handler.dispatchMessage (Handler.java:99)
        at android.os.Looper.loop (Looper.java:193)
        at android.app.ActivityThread.main (ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke (Native Method)
        at com.android.internal.os.RuntimeInit $MethodAndArgsCaller.run (RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:858)
2020-12-14 21: 11: 37.395 21871-21871/com.example.oto I/Process: Sending signal. PID: 21871 SIG: 9
]
  • Answer # 1

    It worked fine with the current code. I don't think there is a problem with the code that is currently presented.

    When I entered Mainactivity.kt as a trial, the audio was opened and played on the computer, but the app could not be opened.

    I'm not sure about this part.

    Launch the app → press the button → play the sound

    Does it mean that it will not be in the state of saying?

    It doesn't matter where you write the MusicManager itself created in the class, so it doesn't matter if it's in MainActivity.kt. You don't have to create a separate class.

    class MainActivity: AppCompatActivity () {
        private lateinit var mediaPlayer: MediaPlayer
        override fun onCreate (savedInstanceState: Bundle?) {
            super.onCreate (savedInstanceState)
            setContentView (R.layout.activity_main)
            // Button for start music
            val buttonStart: Button = findViewById (R.id.start_music)
            // Resister listener
            buttonStart.setOnClickListener {
                startMusic ()
            }
            // Button for stop music
            val buttonStop: Button = findViewById (R.id.stop_music)
            // Resister listener
            buttonStop.setOnClickListener {
                stopMusic ()
            }
        }
        fun startMusic () {
            mediaPlayer = MediaPlayer.create (this, R.raw.test)
            mediaPlayer.isLooping = true
            mediaPlayer.start ()
        }
        fun stopMusic () {mediaPlayer.stop ()
            mediaPlayer.reset ()
            mediaPlayer.release ()
        }
    }

    === Addition to comment
    If the application is down, I think that the error information is in Logcat, so please give me the error log information.

    Below is where the Logcat Error is displayed.

    === Addition to comment
    There is an error on line 19 of MainActivity.kt, and the error is occurring because findVieewById (R.id.start_music) cannot be found.
    Press the blue part of Logcat to jump to the corresponding line.

    Maybe there is no start_music in activity_main.xml?
    I think that it will start if that part does not fall.
    If you don't know how to fix the error, could you please include the contents of activity_main.xml?

    Thank you for your cooperation.

    === Addition to comment
    findViewById (R.id.start_music), This will pick up the ID from the layout you are loadingactivity_main.xmlIf there is no ID called start_music, it will be null. So

    If you want to match the id to xml

    // Button for start music
            val buttonStart: Button = findViewById (R.id.button)
            // Resister listener
            buttonStart.setOnClickListener {
                startMusic ()
            }
            // Button for stop music
            val buttonStop: Button = findViewById (R.id.button2)
            // Resister listener
            buttonStop.setOnClickListener {
                stopMusic ()}

    Or if you want to modify the xml

    <? xml version = "1.0" encoding = "utf-8"?><Button
            android: id = "@ + id/start_music"
            android: layout_width = "wrap_content"
            android: layout_height = "wrap_content"
            android: text = "@ string/start"
            tools: layout_editor_absoluteX = "143dp"
            tools: layout_editor_absoluteY = "119dp" /><Button
            android: id = "@ + id/stop_music"
            android: layout_width = "wrap_content"
            android: layout_height = "wrap_content"
            android: text = "@ string/stop"
            tools: layout_editor_absoluteX = "138dp"
            tools: layout_editor_absoluteY = "363dp" /></androidx.constraintlayout.widget.ConstraintLayout>

    I think that it will start if you fix either of. (You can choose which one to fix)

    Thank you for your cooperation.

  • Answer # 2

    I'm sorry many times.
    I was able to open the app by rewriting activity_main and starting the emulator.
    However, only the STOP button is displayed, and when I tap the STOP button, the app crashes.
    I added the log and the photo of the app to the question.

    Thank you for your cooperation.