I'am trying to play .wav format sounds from raw resource file when i click to the button but nothing happens when i click to the button and there is no logcat error.
My MainActivity.kt:
package com.example.exampleofmusicapp
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
lateinit var soundPool: SoundPool
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
var audioAttrs: AudioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
soundPool = SoundPool.Builder()
.setMaxStreams(2)
.setAudioAttributes(audioAttrs)
.build()
}
else{
soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
}
}
fun playSound1(view: View) {
val sound1 = soundPool.load(this, R.raw.sound1, 1)
soundPool.play(sound1, 1.0f, 1.0f, 1, 0, 1.0f)
}
}
Edit: I have tried this in 2 emulator and a real device but it is not working.
It takes time to load the sound file into memory so change val sound1
to var sound1
, make it global and instantiate it at the end of the onCreate
method like so:
class MainActivity : AppCompatActivity() {
lateinit var soundPool: SoundPool
var sound1 : Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
var audioAttrs: AudioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
soundPool = SoundPool.Builder()
.setMaxStreams(2)
.setAudioAttributes(audioAttrs)
.build()
}
else{
soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
}
sound1 = soundPool.load(this, R.raw.sound1, 1)
}
fun playSound1(view: View) {
if(sound1 != 0) {
soundPool.play(sound1, 1.0f, 1.0f, 1, 0, 1.0f)
}
}
}
Then you could check sound1
value and if it's not equal to 0
so it loaded completely. Also you could use setOnLoadCompleteListener
method of SoundPool
to check this.