<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jaidevnaik on Medium]]></title>
        <description><![CDATA[Stories by Jaidevnaik on Medium]]></description>
        <link>https://medium.com/@jaidevnaik5886?source=rss-30aa77d865c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VwtElRqT_gGwzNV3</url>
            <title>Stories by Jaidevnaik on Medium</title>
            <link>https://medium.com/@jaidevnaik5886?source=rss-30aa77d865c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:11:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaidevnaik5886/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built an Instagram-Style Emoji Game for Chat Apps (With Code!)]]></title>
            <link>https://medium.com/@jaidevnaik5886/how-i-built-an-instagram-style-emoji-game-for-chat-apps-with-code-0bd1fd2d01c2?source=rss-30aa77d865c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd1fd2d01c2</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jaidevnaik]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 19:24:28 GMT</pubDate>
            <atom:updated>2025-04-03T19:24:28.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*FMcnTESgxW1e6e75.gif" /></figure><h3>Ever Wanted to Play a Game Inside Your DMs? Now You Can!</h3><p>Imagine you’re scrolling through your Instagram DMs, and you tap on an emoji message. Suddenly, a game screen pops up, and you can play a fun little challenge based on that emoji! Sounds cool, right? That’s exactly what inspired me to build <strong>an interactive emoji-based game that can be integrated into chat applications</strong>.</p><p>🚀 <strong>In this blog, I’ll show you:</strong></p><ul><li>How I built this feature</li><li>How you can integrate it into your app</li><li>The full source code!</li></ul><h3>🎯 The Idea Behind the Game</h3><p>The concept is simple: <strong>tap on an emoji in a chat, and a mini-game starts</strong>. You collect emojis while avoiding bombs, and your score keeps increasing until you hit a bomb. The goal? <strong>Survive as long as you can!</strong></p><p>💡 <em>Why did I build this?</em></p><ol><li>To make chats more interactive and fun 🎉</li><li>To show how lightweight games can be embedded inside chat apps</li><li>Because, why not? 😆</li></ol><h3>🛠️ Tech Stack &amp; Features</h3><p>✅ <strong>Built with Jetpack Compose</strong> for modern UI ✅ <strong>Uses Kotlin &amp; Android</strong> for seamless performance ✅ <strong>Custom basket &amp; emoji physics</strong> for engaging gameplay ✅ <strong>Vibration effects</strong> for a real feel ✅ <strong>Dynamic difficulty increase</strong> as you score more ✅ <strong>Fully customizable</strong> for any chat platform!</p><h3>🎮 How the Game Works</h3><ul><li>Emojis fall from the top of the screen</li><li>You move the basket left/right to collect them</li><li>Bombs also fall — avoid them at all costs! 💀</li><li>If you collect a bomb, the game is over 😵</li><li>The score increases as you collect more emojis ✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*h3Cj8lMZ-1n0Mj4t.gif" /></figure><h3>📽️ Watch the Game in Action!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*iS6ydceAZ-HLbxmG5RZG6Q.gif" /><figcaption>Gameplay</figcaption></figure><h3>🏗️ The Code (Full Source!)</h3><p>Here’s the complete <strong>Kotlin + Jetpack Compose</strong> code that you can use to build this in your app:</p><pre>import android.graphics.Paint<br>import android.graphics.Path<br>import android.os.Bundle<br>import android.view.LayoutInflater<br>import android.view.View<br>import android.view.ViewGroup<br>import androidx.compose.foundation.Canvas<br>import androidx.compose.foundation.background<br>import androidx.compose.foundation.gestures.detectDragGestures<br>import androidx.compose.foundation.layout.Box<br>import androidx.compose.foundation.layout.BoxWithConstraints<br>import androidx.compose.foundation.layout.fillMaxSize<br>import androidx.compose.foundation.layout.padding<br>import androidx.compose.foundation.layout.wrapContentSize<br>import androidx.compose.foundation.text.BasicText<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.LaunchedEffect<br>import androidx.compose.runtime.getValue<br>import androidx.compose.runtime.mutableStateOf<br>import androidx.compose.runtime.remember<br>import androidx.compose.runtime.setValue<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.graphics.Color<br>import androidx.compose.ui.graphics.nativeCanvas<br>import androidx.compose.ui.graphics.toArgb<br>import androidx.compose.ui.input.pointer.pointerInput<br>import androidx.compose.ui.platform.ComposeView<br>import androidx.compose.ui.text.TextStyle<br>import androidx.compose.ui.unit.dp<br>import androidx.compose.ui.unit.sp<br>import androidx.fragment.app.Fragment<br>import androidx.navigation.fragment.navArgs<br>import kotlinx.coroutines.delay<br>import kotlin.random.Random<br>import android.content.Context<br>import android.os.Build<br>import android.os.VibrationEffect<br>import android.os.Vibrator<br>import android.os.VibratorManager<br><br>class EmojiCollectorGameFragment : Fragment() {<br>    private val args: EmojiCollectorGameFragmentArgs by navArgs()<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?<br>    ): View {<br>        val inputEmoji = args.emoji // Retrieved from navigation arguments<br><br>        return ComposeView(requireContext()).apply {<br>            setContent {<br>                EmojiCollectorGame(requireContext(),inputEmoji = inputEmoji)<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun EmojiCollectorGame(context: Context, inputEmoji: String) {<br>    var basketX by remember { mutableStateOf(200f) }<br>    var fallingObjects by remember { mutableStateOf&lt;List&lt;FallingObject&gt;&gt;(emptyList()) }<br>    var score by remember { mutableStateOf(0) }<br>    var isGameOver by remember { mutableStateOf(false) }<br><br>    val vibrator = remember { getVibrator(context) } // Get the vibrator<br><br>    val basketWidth = 240f<br>    val basketHeight = 100f<br>    val gravity = 12f<br>    var emojiDropTime by remember { mutableStateOf(1300L) }<br>    var bombDropTime by remember { mutableStateOf(1800L) }<br><br>    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {<br>        val screenWidth = constraints.maxWidth.toFloat()<br>        val screenHeight = constraints.maxHeight.toFloat()<br>        val basketY = screenHeight - basketHeight - 10f<br><br>        // Falling Emoji Spawning<br>        LaunchedEffect(Unit) {<br>            fallingObjects = List(2) {<br>                FallingObject(Random.nextFloat() * screenWidth, Random.nextFloat() * (screenHeight / 2), inputEmoji)<br>            }<br>            while (!isGameOver) {<br>                delay(emojiDropTime)<br>                val newEmoji = FallingObject(Random.nextFloat() * (screenWidth - 50f), 0f, inputEmoji)<br>                fallingObjects = fallingObjects + newEmoji<br>            }<br>        }<br><br>        // Bomb Spawning<br>        LaunchedEffect(Unit) {<br>            while (!isGameOver) {<br>                delay(bombDropTime)<br>                val bombEmoji = if (inputEmoji == &quot;💀&quot;) &quot;💀&quot; else &quot;💣&quot;<br>                val newBombs = List(if (Random.nextBoolean()) 2 else 1) {<br>                    FallingObject(Random.nextFloat() * (screenWidth - 50f), 0f, bombEmoji)<br>                }<br>                fallingObjects = fallingObjects + newBombs<br>            }<br>        }<br><br>        // Object Movement<br>        LaunchedEffect(Unit) {<br>            while (!isGameOver) {<br>                delay(16L)<br>                fallingObjects = fallingObjects.map { it.copy(y = it.y + gravity) }<br>                    .filter { it.y &lt; screenHeight }<br>            }<br>        }<br><br>        // Increase Difficulty as Score Increases<br>        LaunchedEffect(score) {<br>            if (score % 10 == 0 &amp;&amp; score &gt; 0) {<br>                emojiDropTime = (emojiDropTime - 20).coerceAtLeast(300)<br>                bombDropTime = (bombDropTime - 5).coerceAtLeast(300)<br>            }<br>        }<br><br>        Box(modifier = Modifier.fillMaxSize().background(if (isGameOver) Color.Red else Color.White)) {<br>            // Game Canvas<br>            Canvas(modifier = Modifier.fillMaxSize()) {<br>                fallingObjects.forEach { obj -&gt;<br>                    drawContext.canvas.nativeCanvas.drawText(<br>                        obj.emoji,<br>                        obj.x,<br>                        obj.y,<br>                        android.graphics.Paint().apply { textSize = 90f }<br>                    )<br>                }<br><br>                // Draw the Inverted Trapezoid Basket<br>                val paint = Paint().apply {<br>                    color = Color.Blue.toArgb()<br>                    style = Paint.Style.FILL<br>                }<br>                val path = Path().apply {<br>                    moveTo(basketX + 10f, basketY + basketHeight)  // Bottom left<br>                    lineTo(basketX + basketWidth - 10f, basketY + basketHeight)  // Bottom right<br>                    lineTo(basketX + basketWidth - 30f, basketY)  // Top right<br>                    lineTo(basketX + 30f, basketY)  // Top left<br>                    close()<br>                }<br>                drawContext.canvas.nativeCanvas.drawPath(path, paint)<br>            }<br><br><br>            // Score Display<br>            BasicText(<br>                text = &quot;Score: $score&quot;,<br>                modifier = Modifier.padding(16.dp),<br>                style = TextStyle(fontSize = 24.sp)<br>            )<br><br>            // Game Over Screen<br>            if (isGameOver) {<br>                BasicText(<br>                    text = &quot;Game Over! Score: $score&quot;,<br>                    modifier = Modifier.fillMaxSize().wrapContentSize(),<br>                    style = TextStyle(fontSize = 32.sp, color = Color.White)<br>                )<br>            }<br>        }<br><br>        // Basket Movement on Drag<br>        Box(modifier = Modifier.fillMaxSize().pointerInput(Unit) {<br>            detectDragGestures { _, dragAmount -&gt;<br>                basketX = (basketX + dragAmount.x).coerceIn(0f, screenWidth - basketWidth)<br>            }<br>        })<br><br>        // Collision Detection and Score Update with Vibration<br>        LaunchedEffect(Unit) {<br>            while (!isGameOver) {<br>                fallingObjects = fallingObjects.filterNot {<br>                    val caught = it.y + 30f &gt;= basketY &amp;&amp; (it.x + 25f) in basketX..(basketX + basketWidth)<br>                    if (caught) {<br>                        if (it.emoji == &quot;💣&quot; || it.emoji == &quot;💀&quot;) {<br>                            isGameOver = true<br>                            vibrateGameOver(vibrator) // 💀💣 Game Over Vibration<br>                        } else {<br>                            score++<br>                            vibrateEmojiCollected(vibrator) // ✅ Emoji Collected Vibration<br>                        }<br>                    }<br>                    caught<br>                }<br>                delay(50L)<br>            }<br>        }<br>    }<br>}<br><br>/**<br> * Get the Vibrator instance (for Android 10+ and lower versions)<br> */<br>fun getVibrator(context: Context): Vibrator {<br>    return if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) {<br>        val vibratorManager = context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager<br>        vibratorManager.defaultVibrator<br>    } else {<br>        context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator<br>    }<br>}<br><br>/**<br> * Vibrate when emoji is collected ✅ (Short vibration)<br> */<br>fun vibrateEmojiCollected(vibrator: Vibrator) {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>        vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE)) // Short vibration<br>    } else {<br>        vibrator.vibrate(100)<br>    }<br>}<br><br>/**<br> * Vibrate when game is over (💀💣 collided) ⚠️ (Long + Strong vibration)<br> */<br>fun vibrateGameOver(vibrator: Vibrator) {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>        vibrator.vibrate(<br>            VibrationEffect.createWaveform(longArrayOf(0, 500, 200, 700), -1) // Strong pulse effect<br>        )<br>    } else {<br>        vibrator.vibrate(longArrayOf(0, 500, 200, 700), -1)<br>    }<br>}<br><br><br><br>// Data class for Falling Objects<br>data class FallingObject(val x: Float, val y: Float, val emoji: String)</pre><h3>🔥 What’s Next?</h3><p>Now that the game is working, <strong>the next step is integration!</strong> You can:</p><ul><li>Embed it in your own chat app 📱</li><li>Add more emoji types (maybe different game modes per emoji?) 🎭</li><li>Enhance the visuals with better graphics 🎨</li><li>Add sound effects 🔊</li></ul><p>If you try this out, let me know! Would love to see your versions. 🚀</p><h3>🤝 Let’s Connect!</h3><p>If you found this useful, follow me for more coding tutorials and fun app ideas. And hey, if you integrate this into your app, send me a DM — I’d love to check it out! 😍</p><p>📢 <strong>Share this with your fellow devs who love fun projects!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd1fd2d01c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Build an Instagram-Style Audio Recorder with Waveform Visualization in Android ]]></title>
            <link>https://medium.com/@jaidevnaik5886/how-to-build-an-instagram-style-audio-recorder-with-waveform-visualization-in-android-74afc1906125?source=rss-30aa77d865c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/74afc1906125</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui-design]]></category>
            <dc:creator><![CDATA[Jaidevnaik]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 15:59:04 GMT</pubDate>
            <atom:updated>2025-02-09T15:59:04.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Instagram and other modern social media platforms have taken audio recording to the next level with <strong>real-time waveform visualizations</strong>. And here you are, staring at your screen like <em>“How the heck do I even draw sound?”</em> 🤯. But don’t worry — by the end of this blog, you’ll go from <em>“What is this sorcery?”</em> to <em>“Look at me, building Instagram-level features!”</em> 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*bTjyOOXuAq4ZWufw41G2SQ.gif" /></figure><p>In this guide, we’ll break it all down and build an <strong>Instagram-style audio recorder waveform</strong> in Android using MediaRecorder, Canvas, and Coroutines. Ready to level up? Let’s dive in! 🎸🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Hpp4oLy6g4sY57OgAovNDA.gif" /><figcaption>Instagram Recorder Visualisation</figcaption></figure><h3>🎯 Overview</h3><p>We will implement:</p><ol><li>A <strong>custom view</strong> to render the waveform (AudioRecorderWaveformView).</li><li>A <strong>recording system</strong> using MediaRecorder.</li><li>A <strong>real-time waveform update</strong> mechanism.</li><li>A <strong>clean UI layout</strong> (because messy UIs are a crime!).</li></ol><h3>1. Creating the Custom Waveform View</h3><p>Let’s get artsy with code! We’ll create a custom View (AudioRecorderWaveformView) that dynamically updates as the user records audio.</p><pre>class AudioRecorderWaveformView @JvmOverloads constructor(<br>    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0<br>) : View(context, attrs, defStyleAttr)<br>{<br><br>    private val wavePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {<br>        style = Paint.Style.FILL<br>    }<br><br>    private val amplitudes = mutableListOf&lt;Float&gt;()<br>    private var barWidth = 8f<br>    private var barGap = 4f<br>    private var cornerRadius = 4f<br>    private var minBarHeightRatio = 0.15f // Minimum bar height as a ratio of view height<br>    private var maxBars: Int = 0<br>    private val barRect = RectF()<br>    private var isInitialized = false<br><br>    init {<br>        val typedArray = context.theme.obtainStyledAttributes(<br>            attrs, R.styleable.AudioRecorderWaveformView, 0, 0<br>        )<br>        try {<br>            barWidth = typedArray.getDimension(<br>                R.styleable.AudioRecorderWaveformView_wave_width, barWidth<br>            )<br>            barGap = typedArray.getDimension(<br>                R.styleable.AudioRecorderWaveformView_wave_gap, barGap<br>            )<br>            cornerRadius = typedArray.getDimension(<br>                R.styleable.AudioRecorderWaveformView_wave_corner_radius, cornerRadius<br>            )<br>            wavePaint.color = typedArray.getColor(<br>                R.styleable.AudioRecorderWaveformView_wave_progress_color,<br>                ContextCompat.getColor(context, android.R.color.white)<br>            )<br>            minBarHeightRatio = typedArray.getFloat(<br>                R.styleable.AudioRecorderWaveformView_wave_min_height_ratio, minBarHeightRatio<br>            )<br>        } finally {<br>            typedArray.recycle()<br>        }<br>    }<br><br>    /**<br>     * Updates the waveform by adding a new amplitude value.<br>     */<br>    fun updateAmplitude(amplitude: Float) {<br>        if (!isInitialized) return<br>        if (amplitudes.size &gt;= maxBars &amp;&amp; amplitudes.isNotEmpty()) {<br>            amplitudes.removeAt(0) // Remove the oldest amplitude to keep the size constant<br>        }<br>        amplitudes.add(amplitude)<br>        invalidate() // Redraw the waveform<br>    }<br><br>    /**<br>     * Resets the waveform by clearing all stored amplitudes.<br>     */<br>    fun resetWaveform() {<br>        amplitudes.clear()<br>        invalidate() // Redraw the view<br>    }<br><br>    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {<br>        super.onSizeChanged(w, h, oldw, oldh)<br>        maxBars = calculateMaxBars()<br>        isInitialized = true<br>    }<br><br>    /**<br>     * Calculates the maximum number of bars that can fit within the available width.<br>     */<br>    private fun calculateMaxBars(): Int {<br>        // Calculate how many bars can fit in the view&#39;s width based on bar width and gap<br>        val totalBarWidth = barWidth + barGap<br>        return if (totalBarWidth &gt; 0) {<br>            (width / totalBarWidth).toInt()<br>        } else {<br>            0<br>        }<br>    }<br><br>    override fun onDraw(canvas: Canvas) {<br>        super.onDraw(canvas)<br>        if (!isInitialized) return<br><br>        val centerY = height / 2f<br>        val minHeight = height * minBarHeightRatio // Set minimum bar height based on ratio<br><br>        // Calculate the total width that will be used by the waveform<br>        val totalWidth = (maxBars * (barWidth + barGap))<br><br>        // Loop through the amplitudes and draw the bars<br>        for (i in amplitudes.indices) {<br>            val x =<br>                (i * (barWidth + barGap)) % totalWidth // This wraps the waveform back to the start when it exceeds totalWidth<br><br>            // Scale amplitude to fit view height<br>            var scaledHeight = (amplitudes[i] * height).coerceAtMost(height.toFloat())<br><br>            // Ensure a minimum height for silent parts<br>            if (scaledHeight &lt; minHeight) {<br>                scaledHeight = minHeight<br>            }<br><br>            val top = centerY - (scaledHeight / 2)<br>            val bottom = centerY + (scaledHeight / 2)<br><br>            barRect.set(x, top, x + barWidth, bottom)<br>            canvas.drawRoundRect(barRect, cornerRadius, cornerRadius, wavePaint)<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*1Cyteg0R-u0Ov_TBFTLMAA.gif" /><figcaption>Our Recorder Visualisation</figcaption></figure><h3>2. Setting Up Audio Recording in MainActivity 🎙️</h3><p>Now, let’s make the magic happen by integrating MediaRecorder to capture and visualize audio.</p><pre>class MainActivity : AppCompatActivity() {<br>    private var _binding: ActivityMainBinding? = null<br><br>    private val binding get() = _binding!!<br>    private var mediaRecorder: MediaRecorder? = null<br>    private var audioFilePath: String = &quot;&quot;<br>    private var isRecording = false<br>    private var recordingStartTime: Long = 0L<br><br>    private var recordingJob: Job? = null<br>    private var waveFormJob: Job? = null<br><br>    private val recorderLauncher =<br>        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -&gt;<br>            if (permissions.all { it.value }) {<br>                startRecording() // Start recording if all permissions are granted<br>            } else {<br>                Toast.makeText(this, &quot;Audio Permissions are required&quot;, Toast.LENGTH_SHORT).show()<br>            }<br>        }<br><br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        _binding = ActivityMainBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br>        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -&gt;<br>            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())<br>            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)<br>            insets<br>        }<br>        initInstagramRecorder()<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        if (isRecording) {<br>            stopRecording(delete = true) // Clean up recording resources if still recording<br>        }<br>        _binding = null<br>    }<br><br>    private fun initInstagramRecorder() {<br>        binding.btnRecord.setOnClickListener {<br>            requestAudioPermissions()<br>        }<br>        binding.ivDeleteAudio.setOnClickListener { stopRecording(delete = true) }<br>        binding.ivSendAudio.setOnClickListener { stopRecording(delete = false) }<br>    }<br><br>    private fun requestAudioPermissions() {<br>        val requiredPermissions = mutableListOf(Manifest.permission.RECORD_AUDIO)<br><br>        if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.Q) { // Only needed for API 28 and below<br>            requiredPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)<br>        }<br><br>        if (requiredPermissions.all {<br>                ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED<br>            }) {<br>            startRecording()<br>        } else {<br>            recorderLauncher.launch(requiredPermissions.toTypedArray())<br>        }<br>    }<br><br>    private fun startRecording() {<br>        if (isRecording) return<br><br>        try {<br>            setupMediaRecorder()<br>            mediaRecorder?.prepare()<br>            mediaRecorder?.start()<br>            isRecording = true<br>            recordingStartTime = System.currentTimeMillis()<br>            showRecordingUI()<br><br>            startUpdatingDuration()<br>            startWaveformUpdates()<br>        } catch (e: Exception) {<br>            e.printStackTrace()<br>            Toast.makeText(this, &quot;Failed to start recording&quot;, Toast.LENGTH_SHORT).show()<br>        }<br>    }<br><br>    private fun setupMediaRecorder() {<br>        audioFilePath = &quot;${externalCacheDir?.absolutePath}/audio_${System.currentTimeMillis()}.mp3&quot;<br>        mediaRecorder = MediaRecorder().apply {<br>            setAudioSource(MediaRecorder.AudioSource.MIC)<br>            setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)<br>            setAudioEncoder(MediaRecorder.AudioEncoder.AAC)<br>            setOutputFile(audioFilePath)<br>        }<br>    }<br><br>    private fun stopRecording(delete: Boolean) {<br>        if (!isRecording) return<br><br>        try {<br>            mediaRecorder?.stop()<br>        } catch (e: IllegalStateException) {<br>            e.printStackTrace()<br>        } finally {<br>            releaseMediaRecorder()<br>        }<br><br>        isRecording = false<br>        stopUpdatingDuration()<br>        stopWaveformUpdates()<br><br>        if (delete) {<br>            deleteAudioFile()<br>        } else {<br>            sendAudio(audioFilePath)<br>        }<br><br>        resetRecordingUI()<br>    }<br><br>    private fun deleteAudioFile() {<br>        File(audioFilePath).delete()<br>        Toast.makeText(this, &quot;Deleted : $audioFilePath&quot;, Toast.LENGTH_LONG).show()<br>    }<br><br>    private fun releaseMediaRecorder() {<br>        try {<br>            mediaRecorder?.release()<br>        } catch (e: Exception) {<br>            e.printStackTrace()<br>        }<br>        mediaRecorder = null<br>    }<br><br>    private fun sendAudio(filePath: String) {<br>        // Handle the audio file upload/send logic here.<br>        Toast.makeText(this, &quot;AudioFile : $filePath&quot;, Toast.LENGTH_LONG).show()<br>    }<br><br>    private fun showRecordingUI() {<br>        binding.clAudioRecording.visibility = View.VISIBLE<br>        binding.btnRecord.visibility = View.GONE<br>    }<br><br>    private fun resetRecordingUI() {<br>        binding.clAudioRecording.visibility = View.GONE<br>        binding.btnRecord.visibility = View.VISIBLE<br>        binding.txtDuration.text = &quot;00:00&quot;<br>        binding.waveformView.resetWaveform() // Reset waveform<br>    }<br><br>    // Start updating the duration display<br>    private fun startUpdatingDuration() {<br>        recordingJob = CoroutineScope(Dispatchers.Main).launch {<br>            while (isRecording) {<br>                val elapsedMillis = System.currentTimeMillis() - recordingStartTime<br>                val seconds = (elapsedMillis / 1000) % 60<br>                val minutes = (elapsedMillis / 1000) / 60<br>                binding.txtDuration.text = String.format(&quot;%02d:%02d&quot;, minutes, seconds)<br>                delay(1000L)<br>            }<br>        }<br>    }<br><br>    // Stop updating the duration display<br>    private fun stopUpdatingDuration() {<br>        recordingJob?.cancel()<br>    }<br><br>    // Start updating the waveform<br>    private fun startWaveformUpdates() {<br>        waveFormJob = lifecycleScope.launch {<br>            while (isRecording) {<br>                val amplitude = mediaRecorder?.maxAmplitude?.toFloat() ?: 0f<br>                val normalizedAmplitude = amplitude / 32767f // Normalize amplitude<br>                binding.waveformView.updateAmplitude(normalizedAmplitude)<br>                delay(50) // Update every 50ms<br>            }<br>        }<br>    }<br><br>    // Stop updating the waveform<br>    private fun stopWaveformUpdates() {<br>        waveFormJob?.cancel()<br>        binding.waveformView.updateAmplitude(0f) // Reset waveform<br>    }<br><br>}</pre><h3>3. UI Layout for a Seamless Experience 🖌️</h3><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/main&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;androidx.appcompat.widget.AppCompatButton<br>        android:id=&quot;@+id/btn_record&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Start Recording&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:id=&quot;@+id/cl_audio_recording&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;52dp&quot;<br>        android:visibility=&quot;gone&quot;<br>        tools:visibility=&quot;visible&quot;<br>        android:focusable=&quot;true&quot;<br>        android:clickable=&quot;true&quot;<br>        android:layout_margin=&quot;8dp&quot;<br>        android:background=&quot;@color/blue&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/txt_duration&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_gravity=&quot;center_horizontal&quot;<br>            android:text=&quot;00:00&quot;<br>            android:textColor=&quot;@color/white&quot;<br>            android:textSize=&quot;14sp&quot;<br>            android:layout_marginEnd=&quot;16dp&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toStartOf=&quot;@+id/iv_send_audio&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br><br>        &lt;com.jaidev.instagramstyleaudiorecorder.AudioRecorderWaveformView<br>            android:id=&quot;@+id/waveformView&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;32dp&quot;<br>            app:wave_width=&quot;4dp&quot;<br>            app:wave_corner_radius=&quot;3dp&quot;<br>            app:wave_gap=&quot;3dp&quot;<br>            app:wave_progress_color=&quot;@color/white&quot;<br>            android:layout_marginHorizontal=&quot;8dp&quot;<br>            app:layout_constraintStart_toEndOf=&quot;@+id/iv_delete_audio&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toStartOf=&quot;@id/txt_duration&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>        &lt;ImageView<br>            android:id=&quot;@+id/iv_delete_audio&quot;<br>            android:layout_width=&quot;32dp&quot;<br>            android:layout_height=&quot;32dp&quot;<br>            android:src=&quot;@drawable/ic_delete&quot;<br>            android:layout_marginStart=&quot;16dp&quot;<br>            android:padding=&quot;4dp&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>        &lt;ImageView<br>            android:id=&quot;@+id/iv_send_audio&quot;<br>            android:layout_width=&quot;32dp&quot;<br>            android:layout_height=&quot;32dp&quot;<br>            android:layout_marginEnd=&quot;16dp&quot;<br>            android:padding=&quot;4dp&quot;<br>            android:src=&quot;@drawable/baseline_arrow_upward_24&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;/&gt;<br><br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br><br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*nyFCQLtCpzGkJ6ZQUP1XuA.gif" /><figcaption>S<strong>hort clip</strong> of the UI in action, where tapping the record button starts the waveform animation.</figcaption></figure><h3>4. Adding Required Permissions 🔐</h3><pre>&lt;uses-permission android:name=&quot;android.permission.RECORD_AUDIO&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;</pre><h3>5. Frequently Asked Questions (FAQ) 🤔</h3><h4>1. How do I create a real-time waveform in Android?</h4><p>You can achieve this by continuously polling the microphone amplitude and updating a custom View dynamically.</p><h4>2. What is the best way to record audio with a waveform UI in Android?</h4><p>Using MediaRecorder for recording and a Canvas-based View for real-time visualization ensures smooth performance.</p><h4>3. Does Android support real-time audio visualization?</h4><p>Yes! By fetching amplitude data periodically and updating a View, you can create smooth audio visualizations.</p><h3>Conclusion 🎉</h3><p>With these implementations, we have successfully built an <strong>Instagram-style audio recorder with real-time waveform visualization</strong> in Android. This setup ensures smooth recording with an engaging UI.</p><p>For the complete source code, visit the <strong>GitHub repository</strong>: <a href="https://github.com/jaidevnaik5886/Instagram-Audio-Waveform">GitHub Link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*xzuxJ5TevGm5ztWTs7vZhw.gif" /></figure><p>Happy (Re)coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74afc1906125" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>