I create Application Sounds Of Animals But I have a Problem The Sounds are not playing The Code of list of Animals with Name , Image and Sound
listanimales.add(animals("Cat",R.drawable.a1,R.raw.a1))
listanimales.add(animals("Dog",R.drawable.a2,R.raw.a2))
listanimales.add(animals("Fox",R.drawable.a3,R.raw.a3))
override fun getView(postion: Int, p1: View?, p2: ViewGroup?): View? {
var anum = mylistofAnimals[postion]
var myView = layoutInflater.inflate(R.layout.design,null)
myView.anImage.setImageResource(anum.aImage!!)
myView.anName.text = anum.aName!!
myView.anImage.setOnClickListener {
player = MediaPlayer()
try {
player!!.setDataSource(anum.aSound)
player!!.prepare()
player!!.start()
}catch (ex:Exception){
}
}
return myView
}
The End is my Class
class animals{
var aName:String?=null
var aImage:Int?=null
var aSound:Int?=null
constructor(aName:String,aImage:Int,aSound:Int){
this.aName = aName
this.aImage = aImage
this.aSound = aSound
}
}
What's the Problem ?
Try using the following code in kotlin:
player = MediaPlayer()
player.create(this,anum.aSound)
player!!.start()
the below code is converted from java to kotlin. Hope it can also run.
EDIT: acc to @bakawali suggestion instead of this use view to get context.
val mediaPlayer = MediaPlayer.create(mView.Context, resID)
mediaPlayer.start()
Where your resID will be as follow:
var resID = getResources().getIdentifier(anum.aSound, "raw", getPackageName())
make sure anum.aSound is just the name of the sound with no extension
Example: Sound file : ringtone.mp3 - write:
.getIndentifier("ringtone","raw",getPackageName())
The above answer helped me but this is what worked for me in my current project. I hope it helps someone else in the near future.
fun playSound() {
var resId = getResources().getIdentifier(R.raw.sawing.toString(),
"raw", activity?.packageName)
val mediaPlayer = MediaPlayer.create(activity, resId)
mediaPlayer.start()
}
sawing is the name of my file in the raw folder. I am using this function inside a fragment. If you don't understand Ill happily explain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With