How to Play an arbitrary tone in Android using Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to Play an arbitrary tone in Android using Kotlin

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:orientation="vertical"
   android:padding="16dp"
   tools:context=".MainActivity">
   <ImageView
      android:layout_width="200dp"
      android:layout_height="300dp"
      android:src="@drawable/ic_music" />
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Increase the emulator Volume, Listen to the arbitrary tone!"
      android:textColor="@android:color/background_dark"
      android:textSize="16sp"
      android:textStyle="bold|italic" />
</LinearLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import kotlin.experimental.and
import kotlin.math.sin
class MainActivity : AppCompatActivity() {
   private val duration = 10
   private val sampleRate = 8000
   private val numSamples = duration * sampleRate
   private val sample = DoubleArray(numSamples)
   private val generatedSnd = ByteArray(2 * numSamples)
   var handler: Handler = Handler()
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   override fun onResume() {
      super.onResume()
      val thread = Thread(Runnable {
         genTone()
         handler.post { playSound() }
      })
      thread.start()
   }
   private fun genTone() {
      for (i in 0 until numSamples) {
         val freqOfTone = 440.0
         sample[i] =
         sin(2 * Math.PI * i / (sampleRate / freqOfTone))
      }
      var idx = 0
      for (dVal in sample) {
         val `val` = (dVal * 32767).toShort()
         generatedSnd[idx++] = `val`.and(0x00ff).toByte()
         generatedSnd[idx++] = `val`.and(0xff00 ushr 8).toByte()
      }
   }
   private fun playSound() {
      val audioTrack = AudioTrack(
         AudioManager.STREAM_MUSIC,
         sampleRate, AudioFormat.CHANNEL_OUT_MONO,
         AudioFormat.ENCODING_PCM_16BIT, generatedSnd.size,
         AudioTrack.MODE_STATIC
      )
      audioTrack.write(generatedSnd, 0, generatedSnd.size)
      audioTrack.play()
   }
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

raja
Published on 26-May-2020 11:34:44
Advertisements