Android Studio plays video and audio files and solves the project error java.lang.RuntimeException: java.io.IOException: setDataSource failed.

1: Use MediaPlayer to play audio files to achieve play, pause, and replay functions.

1. Create a new blank project MediaPlayer, create a new directory raw under res, and put music.mp3 into the raw directory, as shown in the following figure:

2.activity_main.xml

Use linear layout LinearLayout, arrange vertically android:orientation=”vertical”, and place three buttons. The code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@ + id/play_button"
        android:layout_width="240dp"
        android:layout_height="54dp"
        android:text="Play"
        android:layout_marginTop="100dp"
        tools:layout_editor_absoluteX="50dp"
        tools:layout_editor_absoluteY="82dp"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@ + id/pause_button"
        android:layout_width="240dp"
        android:layout_height="51dp"
        android:text="pause"
        tools:layout_editor_absoluteX="50dp"
        tools:layout_editor_absoluteY="165dp"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@ + id/stop_button"
        android:layout_width="234dp"
        android:layout_height="53dp"
        android:text="Stop"
        tools:layout_editor_absoluteX="50dp"
        tools:layout_editor_absoluteY="249dp"
        tools:ignore="MissingConstraints" />

</LinearLayout>

3.The key code of Mainactivity.java is as follows:

package cn.itcast.mediaplayer;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button playButton;
    private Button pauseButton;
    private Button stopButton;
    private MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playButton = findViewById(R.id.play_button);
        pauseButton = findViewById(R.id.pause_button);
        stopButton = findViewById(R.id.stop_button);
        playButton.setOnClickListener(this);
        pauseButton.setOnClickListener(this);
        stopButton.setOnClickListener(this);
        initMediaPlayer();
    }
    private void initMediaPlayer(){
        Uri uri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + R.raw.music);
        try {
            mediaPlayer.setDataSource(this,uri);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.play_button:
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start(); // Start playing
                }
                break;
            case R.id.pause_button:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause(); // Pause playback
                }
                break;
            case R.id.stop_button:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.reset(); // Stop playing initMediaPlayer();
                    initMediaPlayer();
                    break;
                }
        }
    }
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}

4. Configuration file AndroidManifest.xml, the code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />

    <application

        android:requestLegacyExternalStorage="true"

        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.MediaPlayer"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

5. Available by running the project

6. Problems encountered:

1. Error reported in the project: Caused by: java.lang.RuntimeException: java.io.IOException: setDataSource failed.

Solution:

Errors usually indicate a problem when setting up the data source. To resolve this error, you can try the following steps:

  1. Check the file path: Make sure the data source path you set is correct. Check that the file exists and make sure that the slash symbol used in the path is correct (either forward or backslash depending on the operating system).

  2. Check permissions: If you are accessing a file on external storage, make sure you have added the appropriate read permissions in the AndroidManifest.xml file.

  3. Make sure the file is readable: Make sure the file is not occupied by another application or corrupted. Try opening the file with another player or text editor to make sure the file can be accessed and read properly.

  4. Use the correct file format: Check that the file’s format matches what your application supports. Try using supported file formats for testing.

  5. Consider coding errors: If none of the above steps resolve the issue, there may be an error in setting up the data source in your code. Double-check your code and make sure you don’t make any mistakes when setting up the data source, such as checking that exceptions are handled correctly.

Only one data source setting method can be used at runtime. Also make sure that the file paths and resource names are correct, and that your application has permission to read external storage and resources.

2. Use VideoView to create a video player, play video files, and implement play, pause, and replay functions. The key code is as follows:

Create a new project, create a new directory raw under res, and put luhan.mp4 in the raw directory.

1.activity_main.xml

Use linear layout LinearLayout, vertically arrange android:orientation=”vertical”, place a VideoView control and three buttons, the key code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <VideoView
        android:id="@ + id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="MissingConstraints" />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:id="@ + id/play_button"
        android:layout_width="75dp"
        android:layout_height="48dp"
        android:text="play"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="50dp"
        tools:layout_editor_absoluteY="292dp" />

    <Button
        android:id="@ + id/pause_button"
        android:layout_width="84dp"
        android:layout_height="47dp"
        android:text="Pause"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="159dp"
        tools:layout_editor_absoluteY="292dp" />

    <Button
        android:id="@ + id/stop_button"
        android:layout_width="73dp"
        android:layout_height="46dp"
        android:text="re-"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="275dp"
        tools:layout_editor_absoluteY="292dp" />
    </LinearLayout>

</LinearLayout>

2. Create the directory raw under the res folder and add luhan.mp4, as shown in the figure below:

3.Mainactivity.java code is as follows:

package cn.itcast.myvideoview;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private VideoView videoView;
    private Button playButton;
    private Button stopButton;
    private Button pauseButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoView =findViewById(R.id.video_view);
        playButton = findViewById(R.id.play_button);
        pauseButton = findViewById(R.id.pause_button);
        stopButton = findViewById(R.id.stop_button);
        initVideoPath();
        playButton.setOnClickListener(this);
        pauseButton.setOnClickListener(this);
        stopButton.setOnClickListener(this);
    }

    private void initVideoPath() {
        Uri uri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + R.raw.luhan);
        videoView.setVideoURI(uri);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_button:
                if (!videoView.isPlaying()) {
                    videoView.start(); // Start playing
                } break;
            case R.id.pause_button:
                if (videoView.isPlaying()) {
                    videoView.pause(); // Play temporarily
                } break;
            case R.id.stop_button:
                if (videoView.isPlaying()) {
                    videoView.resume(); //Replay
                } break;}
    }

    protected void onDestroy() {
        super.onDestroy();
        if (videoView != null) {
            videoView.suspend();
        }
    }

}

4. Configuration file AndroidManifest.xml, the code is as follows:

5. Run the project, the results are as follows:

6. Problems encountered

Error reported in the projectjava.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.VideoView.setVideoURI(android.net.Uri)’ on a null object reference

Solution:

In the onCreate() method, there is no support for the play button (playButton), pause button (pauseButton) and stop button (stopButton code>) to initialize. This causes a null pointer exception when setting up the click listener.

To solve this problem, you need to find the views for these buttons and initialize them in the onCreate() method, similar to how you initialized the videoView.

Add the following code to your onCreate() method:

playButton = findViewById(R.id.play_button);
pauseButton = findViewById(R.id.pause_button);
stopButton = findViewById(R.id.stop_button);

This way, you initialize the buttons correctly and avoid null pointer exceptions.