Audiotrack播放PCM数据

package com.example.audiotrack;

import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.audiotrack.databinding.ActivityMainBinding;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    private DataInputStream mInputStream;//输入流,用于读文件
    private AudioTrack mAudioTrack;
    AudioFormat audioFormat;
    private byte[] tmpBuf;//临时存储buffer
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        //Create AudioTrack
        AudioAttributes attributes;
        audioFormat = new AudioFormat.Builder().build();
        //int bufSize = AudioTrack.getMinBufferSize(192000,AudioFormat.CHANNEL_OUT_5POINT1,AudioFormat.ENCODING_IEC61937);
        int bufSize = AudioTrack.getMinBufferSize(44100,AudioFormat.CHANNEL_IN_STEREO,AudioFormat.ENCODING_PCM_16BIT);//获取最小buffer的大小
        bufSize *=2;//对最小buff乘2
        Log.d(TAG,"getMinBufferSize*2 "+bufSize+" bytes");
        //mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 192000,AudioFormat.CHANNEL_OUT_5POINT1, AudioFormat.ENCODING_IEC61937,bufSize, AudioTrack.MODE_STREAM);
        创建一个44100hz,双通道,16位有符号格式的audiotrack
        mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT,bufSize, AudioTrack.MODE_STREAM);
        mAudioTrack.play();//启动AudioTrack
        tmpBuf = new byte[24576];
        File file = new File("/data/wangfeichuanq.pcm");//从文件读取pcm数据
        try {
            mInputStream = new DataInputStream(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        Log.d(TAG,"audioTrack state "+mAudioTrack.getState());

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAnchorView(R.id.fab)
                        .setAction("Action", null).show();
                Runnable runPlay = new Runnable(){
                    @Override
                    public void run() {
                        int buflen;
                        while(true) {
                            try {
                                //每次循环读取24576字节的数据
                                buflen = mInputStream.read(tmpBuf, 0, 24576);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                            //写入AudioTrack;
                            mAudioTrack.write(tmpBuf, 0, 24576);
                            //Log.d(TAG, "write");
                        }
                    }
                };
                runPlay.run();

            }
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

一、以上是Activity的代码。

二、以下是androidstudio配置

plugins {
    alias(libs.plugins.android.application)
}

android {
    namespace = "com.example.audiotrack"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.example.audiotrack"
        minSdk = 29
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    buildFeatures {
        viewBinding = true
    }
}

dependencies {

    implementation(libs.appcompat)
    implementation(libs.material)
    implementation(libs.constraintlayout)
    implementation(libs.navigation.fragment)
    implementation(libs.navigation.ui)
    testImplementation(libs.junit)
    androidTestImplementation(libs.ext.junit)
    androidTestImplementation(libs.espresso.core)
}

三、点击邮件按钮

相关推荐
学习嵌入式的小羊~1 小时前
RV1126+FFMPEG推流项目(7)AI音频模块编码流程
人工智能·ffmpeg·音视频
学习嵌入式的小羊~1 小时前
RV1126+FFMPEG推流项目(8)AENC音频编码模块
ffmpeg·音视频
yjhqukq10 小时前
递归40题!再见递归
c语言·数据结构·c++·算法·链表·双向链表
飞yu流星10 小时前
c++ string
开发语言·c++·算法
荣--10 小时前
编程练习:编写一个监听者模式类
c++·设计模式·observer·监听者模式
beyond谚语11 小时前
(一)相机标定——四大坐标系的介绍、对应转换、畸变原理以及OpenCV完整代码实战(C++版)
c++·数码相机·opencv
爱吃涮毛肚的肥肥(暂时吃不了版)11 小时前
Leetcode——链表:143.重排链表
数据结构·c++·后端·算法·leetcode·链表·职场和发展
忆源12 小时前
Linux高级--3.3.1 C++ spdlog 开源异步日志方案
java·c++·开源
0xCC说逆向13 小时前
Windows图形界面(GUI)-QT-C/C++ - Qt List Widget详解与应用
c语言·开发语言·c++·windows·qt·win32·1024程序员节