如何在布局activity中显示随机声音结果的值,以便播放

how to display the value of random sound results in the layout activity so that it can be played

原始 android 工作室文件夹中有 3 个音频:

声音1.mp3 声音2.mp3 Sound3.mp3

然后,我想使用 fisher yates 随机播放算法进行音频随机播放。 下面的代码是否正确?还是需要先初始化?

/ package com.example.once;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
import java.util.Arrays;



public class Main4Activity extends AppCompatActivity {
// Java Program to shuffle a given array

    public static class ShuffleRand {
        // A Function to generate a random permutation of arr []
        static void randomize (String arr [], int n) {
            // Creating a object for Random class
            Random r = new Random ();

            // Start from the last element and swap one by one. We don't
            // need to run for the first element that's why i> 0
            for (int i = n - 1; i> 0; i--) {

                // Pick a random index from 0 to i
                int j = r.nextInt (i + 1);

                // Swap arr [i] with the element at random index
                String temp = arr [i];
                arr [i] = arr [j];
                arr [j] = temp;
            }
            // Prints the random array
            System.out.println (arr [0]);
            System.out.println (Arrays.toString (arr));
        }

        // Driver Program to test above function
        public static void main (String [] args) {

            String [] arr = {"R.raw.sound1, R.raw.sound2, R.raw.sound3"};
            int n = arr.length;
            randomize (arr, n);
        }

    }
}

获得随机值(arr [0])后,我想在播放按钮的 .xml activity 布局上使用 onClick 输入值(arr [0])播放歌曲。怎么做?

<ImageView
        android: id = "@ + id / imageView5"
        android: layout_width = "75dp"
        android: layout_height = "80dp"
        android: onClick = "playSong"
        android: layout_marginTop = "50dp"
        app: layout_constraintEnd_toEndOf = "parent"
        app: layout_constraintStart_toStartOf = "parent"
        app: layout_constraintTop_toBottomOf = "@ + id / imageView8"
        app: srcCompat = "@ drawable / play" />

你可以这样做:

private MediaPlayer mMediaPlayer;

public void stopSong() {
    if (mMediaPlayer != null) {
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
}

public void playSong(Context c, int rid) {
    stop();

    mMediaPlayer = MediaPlayer.create(c, rid);
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            stop();
        }
    });

    mMediaPlayer.start();
}

所以你可以调用这个函数:

 playSong(this, getResources().getIdentifier(arr[0], "raw", getPackageName());