Guozhen AIGlobal AI field notes and model intelligence

English translation

Android Audio and Video Playback

Published:

Category: Android Development

Read time: 2 min

Reads: 0

Lesson #23Views are counted together with the original Chinese articleImages are preserved from the source page

AI Article Decision Snapshot

Turn the lesson into workflow, model, budget, and security checks before choosing tools.

Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.

Workflow fit

Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.

Model or tool decision

Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.

Budget and usage signal

Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.

Security and privacy review

Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.

In this chapter, we will delve into implementing audio and video playback functionality in Android applications. Audio-visual processing is an indispensable feature of modern apps; mastering this skill significantly enhances app interactivity and user experience. We’ll demonstrate—through practical examples—how to use both MediaPlayer and ExoPlayer to play audio and video.

Fundamentals

Before diving in, let’s review the core components involved in audio/video playback. Android provides several built-in approaches for handling media:

  • MediaPlayer: A standard, system-provided media playback API for playing local audio and video files. It’s simple to use but lacks flexibility and advanced features.
  • ExoPlayer: An open-source, highly customizable media player library developed by Google. Compared to MediaPlayer, it offers superior extensibility, robust streaming support (e.g., DASH, HLS), and fine-grained control over playback behavior.

We’ll now walk through usage patterns for both APIs, accompanied by concrete code examples.

Playing Audio with MediaPlayer

Initializing MediaPlayer

First, add a button in your layout file to trigger audio playback:

<Button
    android:id="@+id/playButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Play Audio" />

Next, initialize MediaPlayer in your Activity and set its audio source:

class MainActivity : AppCompatActivity() {

    private lateinit var mediaPlayer: MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val playButton: Button = findViewById(R.id.playButton)

        playButton.setOnClickListener {
            playAudio()
        }

        mediaPlayer = MediaPlayer.create(this, R.raw.sample_audio) // 'sample_audio' is an audio file placed under res/raw/
    }

    private fun playAudio() {
        if (!mediaPlayer.isPlaying) {
            mediaPlayer.start()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.release() // Release MediaPlayer resources to prevent memory leaks
    }
}

Code Explanation

  1. We instantiate MediaPlayer using MediaPlayer.create(), which loads and prepares the audio resource synchronously.
  2. The playAudio() method starts playback only if it isn’t already playing—avoiding redundant calls to start().
  3. In onDestroy(), we explicitly call mediaPlayer.release() to free underlying native resources and avoid memory leaks.

Playing Video with ExoPlayer

Compared to MediaPlayer, ExoPlayer delivers richer capabilities—including adaptive streaming, custom renderers, and seamless error recovery. First, declare the ExoPlayer dependency in your build.gradle file:

implementation 'com.google.android.exoplayer:exoplayer:2.X.X' // Use the latest stable version

Initializing ExoPlayer

Add a PlayerView to your layout to render the video:

<com.google.android.exoplayer2.ui.PlayerView
    android:id="@+id/player_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fit" />

Then initialize ExoPlayer in your VideoActivity:

class VideoActivity : AppCompatActivity() {

    private lateinit var player: SimpleExoPlayer
    private lateinit var playerView: PlayerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)

        playerView = findViewById(R.id.player_view)
        player = ExoPlayer.Builder(this).build()
        playerView.player = player

        val mediaItem = MediaItem.fromUri("asset:///sample_video.mp4") // Replace with your actual video URI (local or remote)
        player.setMediaItem(mediaItem)
        player.prepare()
    }

    override fun onStart() {
        super.onStart()
        player.playWhenReady = true // Begin playback as soon as preparation completes
    }

    override fun onStop() {
        super.onStop()
        player.playWhenReady = false // Pause playback when activity is no longer visible
    }

    override fun onDestroy() {
        super.onDestroy()
        player.release() // Release ExoPlayer resources
    }
}

Code Explanation

  1. PlayerView serves as the UI surface for rendering video and displaying playback controls.
  2. We construct a SimpleExoPlayer instance and assign it to playerView.player.
  3. MediaItem.fromUri() specifies the media source—supporting local assets (asset:///), raw resources (android.resource://), or remote URLs (https://).
  4. In onStart(), setting playWhenReady = true ensures playback resumes automatically once prepared.
  5. In onStop(), setting playWhenReady = false pauses playback without releasing resources—ideal for backgrounding scenarios.

Summary

In this chapter, we covered how to implement audio playback using MediaPlayer and video playback using ExoPlayer. These tools empower developers to deliver rich, responsive multimedia experiences—key to engaging modern users.

In the next chapter, we’ll explore camera integration, enabling real-time image capture and video recording to further expand your app’s multimedia capabilities—and unlock new dimensions of creativity and interaction.

We hope this chapter has been helpful! If you have questions or need deeper examples, feel free to ask!

Apply This Lesson

Turn this article into AI software, model, API, and security decisions.

English Article FAQ

Use this article as evidence before choosing AI tools

How should I use this AI Tutorials article?

Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.

Is this English article different from the Chinese original?

The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.

What should I read after Android Audio and Video Playback?

Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.

Can this article alone choose an AI product or model?

No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.

Continue

Keep reading from here

Browse English site

Reader Messages

Reader messages

Questions, corrections, extra sources, or hands-on results can be left here. No login is required.

Max 800 characters

To reduce spam, each message is checked for length, link count, and posting frequency.

0/800

Messages

0 messages
Loading messages...