MediaPlayer播放raw文件夹下的文件

Android MediaPlayer播放raw文件夹下的文件

1. activity布局

2. Activity代码

package com.example.myraw;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;
    private Button button;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioAttributes attributes = new  AudioAttributes.Builder()
                        .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                        .build();
                mediaPlayer.setAudioAttributes(attributes);
                uri = Uri.parse("android.resource://com.example.myraw/" + R.raw.h);
                try {
                    mediaPlayer.setDataSource(getApplicationContext(), uri);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        mediaPlayer = new MediaPlayer();
    }
}

3. 主要代码

3.1 设置音频路径
uri = Uri.parse("android.resource://com.example.myraw/" + R.raw.h);
3.2 MediaPlayer音频设置
AudioAttributes attributes = new  AudioAttributes.Builder()
          .setLegacyStreamType(AudioManager.STREAM_MUSIC)
          .build();
mediaPlayer.setAudioAttributes(attributes);

4. 添加raw文件夹及资源

4.1添加raw文件夹

MediaPlayer播放raw文件夹下的文件_第1张图片
MediaPlayer播放raw文件夹下的文件_第2张图片

4.2复制资源到raw目录

https://blog.csdn.net/qq_40733723/article/details/89763047

参考链接:
https://blog.csdn.net/qq_40733723/article/details/89763047
https://blog.csdn.net/yanlinembed/article/details/51887642

你可能感兴趣的:(android)