Java 音频曲目在Android中不起作用
我是Android新手。我正在开发一个应用程序,它使用Java 音频曲目在Android中不起作用,java,android,multithreading,audio,audiorecord,Java,Android,Multithreading,Audio,Audiorecord,我是Android新手。我正在开发一个应用程序,它使用AudioRecorder和AudioTrack进行录制和播放。除此之外,我还尝试读取和显示录制声音的振幅值 这是我的班级 public class MainActivity extends AppCompatActivity { private static final String TAG = "RecordSound"; private int BufferSize; byte[] buffer = new byte[BufferSi
AudioRecorder
和AudioTrack
进行录制和播放。除此之外,我还尝试读取和显示录制声音的振幅值
这是我的班级
public class MainActivity extends AppCompatActivity {
private static final String TAG = "RecordSound";
private int BufferSize;
byte[] buffer = new byte[BufferSize];
/* AudioRecord and AudioTrack Object */
private AudioRecord record = null;
private AudioTrack track = null;
/* Audio Configuration */
private int sampleRate = 8000;
private int channelConfig = AudioFormat.CHANNEL_IN_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
private boolean isRecording = true;
private Thread recordingThread = null;
private double lastLevel = 0;
private Thread thread;
private static final int SAMPLE_DELAY = 75;
MediaPlayer mediaPlayer;
RelativeLayout layout;
private ImageView tankHolder;
TextView text;
Button play;
String filename;
final Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tankHolder = (ImageView)findViewById(R.id.tankHolder);
text=(TextView)findViewById(R.id.result_text);
layout=(RelativeLayout)findViewById(R.id.linear);
play=(Button)findViewById(R.id.btnStartPlay);
try {
BufferSize = AudioRecord.getMinBufferSize(sampleRate,
channelConfig, audioFormat);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
//calling MediaPlayer for alarmtone when the tank is almost full
mediaPlayer = MediaPlayer.create(this, R.raw.tone);
startRecording();
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
stopRecording();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void stopRecording() throws IOException{
if (null != record) {
isRecording = false;
record.stop();
record.release();
record = null;
recordingThread = null;
mHandler.post(runRecord);
mediaPlayer.stop();
mediaPlayer.release();
}
}
final Runnable runRecord=new Runnable() {
@Override
public void run() {
text.setText("working");
try {
PlayShortAudioFileViaAudioTrack("/sdcard/recorded.pcm");
} catch (IOException e) {
e.printStackTrace();
}
}
};
private void PlayShortAudioFileViaAudioTrack(String filePath) throws IOException{
// We keep temporarily filePath globally as we have only two sample sounds now..
if (filePath==null)
return;
//Reading the file..
File file = new File(filePath); // for ex. path= "/sdcard/samplesound.pcm" or "/sdcard/samplesound.wav"
byte[] byteData = new byte[(int) file.length()];
Log.d(TAG, (int) file.length()+"");
FileInputStream in = null;
try {
in = new FileInputStream( file );
in.read( byteData );
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Set and push to audio track..
int intSize = android.media.AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
Log.d(TAG, intSize+"");
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, intSize, AudioTrack.MODE_STREAM);
at.play();
// Write the byte array to the track
at.write(byteData, 0, byteData.length);
at.stop();
at.release();
}
private void startRecording()
{
record = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate,
channelConfig, audioFormat, BufferSize);
if (AudioRecord.STATE_INITIALIZED == record.getState())
record.startRecording();
isRecording = true;
/* Run a thread for Recording */
recordingThread = new Thread(new Runnable() {
@Override
public void run() {
writeAudioDataToFile();
}
},"AudioRecorder Thread");
recordingThread.start();
thread = new Thread(new Runnable() {
public void run() {
while(thread != null && !thread.isInterrupted()){
//Let's make the thread sleep for a the approximate sampling time
try{
Thread.sleep(SAMPLE_DELAY);}catch(InterruptedException ie){ie.printStackTrace();}
readAudioBuffer();//After this call we can get the last value assigned to the lastLevel variable
runOnUiThread(new Runnable() {
@Override
public void run() {
if(lastLevel >= 7 && lastLevel <= 15){
text.setTextColor(getResources().getColor(R.color.Blue));
layout.setBackgroundColor(Color.RED);
tankHolder.setImageResource(R.drawable.ftank);
if (!mediaPlayer.isPlaying()){
mediaPlayer.start();
}
text.setText(String.valueOf(lastLevel));
}else
if(lastLevel > 50 && lastLevel <= 100){
text.setText(String.valueOf(lastLevel));
text.setTextColor(getResources().getColor(R.color.Orange));
layout.setBackgroundColor(Color.WHITE);
tankHolder.setImageResource(R.drawable.htank);
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}else
if(lastLevel > 100 && lastLevel <= 170){
text.setText(String.valueOf(lastLevel));
text.setTextColor(getResources().getColor(R.color.Yellow));
layout.setBackgroundColor(Color.WHITE);
tankHolder.setImageResource(R.drawable.qtank);
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(lastLevel > 170){
text.setText(String.valueOf(lastLevel));
text.setTextColor(getResources().getColor(R.color.Blue));
layout.setBackgroundColor(Color.WHITE);
tankHolder.setImageResource(R.drawable.qtank);
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
}
});
}
}
},"AudioRecorder Thread");
thread.start();
}
private void writeAudioDataToFile()
{
byte data[] = new byte[BufferSize];
/* Record audio to following file */
String filePath = "/sdcard/recorded.pcm";
filename = Environment.getExternalStorageDirectory().getAbsolutePath();
filename +="/audiofile.pcm";
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read_bytes = 0;
if(null != os){
while(isRecording)
{
read_bytes = record.read(data, 0, BufferSize);
if(AudioRecord.ERROR_INVALID_OPERATION != read_bytes){
try {
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void readAudioBuffer() {
try {
short[] buffer = new short[BufferSize];
int bufferReadResult = 1;
if (record != null) {
// Sense the voice...
bufferReadResult = record.read(buffer, 0, BufferSize);
double sumLevel = 0;
for (int i = 0; i < bufferReadResult; i++) {
sumLevel += buffer[i];
}
lastLevel = Math.abs((sumLevel / bufferReadResult));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public类MainActivity扩展了AppCompatActivity{
私有静态最终字符串标记=“RecordSound”;
私有int缓冲区大小;
字节[]缓冲区=新字节[BufferSize];
/*录音和音轨对象*/
私人录音记录=空;
专用音轨=空;
/*音频配置*/
私人int采样器=8000;
private int channelConfig=AudioFormat.CHANNEL\u在单声道中;
专用int audioFormat=audioFormat.ENCODING_PCM_16位;
私有布尔值isRecording=true;
私有线程recordingThread=null;
私有双级别=0;
私有线程;
专用静态最终int样本_延迟=75;
媒体播放器;
相对布局;
私家油轮;
文本查看文本;
按钮播放;
字符串文件名;
最终处理程序mHandler=新处理程序();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
油罐架=(图像视图)findViewById(R.id.tankHolder);
text=(TextView)findViewById(R.id.result\u text);
布局=(相对长度)findViewById(R.id.linear);
play=(按钮)findViewById(R.id.btnStartPlay);
试一试{
BufferSize=AudioRecord.getMinBufferSize(采样器,
channelConfig(音频格式);
}捕获(例外e){
e、 printStackTrace();
}
}
@凌驾
受保护的void onResume(){
super.onResume();
//油箱快满时呼叫MediaPlayer发出警报音
mediaPlayer=mediaPlayer.create(这个,R.raw.tone);
startRecording();
play.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
试一试{
停止录制();
}捕获(IOE异常){
e、 printStackTrace();
}
}
});
}
私有void stopRecording()引发IOException{
if(null!=记录){
isRecording=false;
record.stop();
record.release();
记录=null;
recordingThread=null;
mHandler.post(运行记录);
mediaPlayer.stop();
mediaPlayer.release();
}
}
final Runnable runRecord=new Runnable(){
@凌驾
公开募捐{
text.setText(“工作”);
试一试{
PlayShortAudioFileViaAudioTrack(“/sdcard/recorded.pcm”);
}捕获(IOE异常){
e、 printStackTrace();
}
}
};
private void PlayShortAudioFileViaAudioTrack(字符串文件路径)引发IOException{
//我们暂时全局保留filePath,因为现在只有两个示例声音。。
if(filePath==null)
返回;
//正在读取文件。。
File File=new File(filePath);//对于ex.path=“/sdcard/samplesound.pcm”或“/sdcard/samplesound.wav”
byte[]byteData=新字节[(int)file.length()];
Log.d(TAG,(int)file.length()+“”);
FileInputStream in=null;
试一试{
in=新文件输入流(文件);
in.read(byteData);
in.close();
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
//设置并按入音频曲目。。
int intSize=android.media.AudioTrack.getMinBufferSize(8000,AudioFormat.CHANNEL\u OUT\u MONO,AudioFormat.ENCODING\u PCM\u 16位);
Log.d(标记,intSize+“”);
AudioTrack at=新的AudioTrack(AudioManager.STREAM\u MUSIC,8000,AudioFormat.CHANNEL\u OUT\u MONO,AudioFormat.ENCODING\u PCM\u 16位,intSize,AudioTrack.MODE\u STREAM);
at.play();
//将字节数组写入磁道
at.write(byteData,0,byteData.length);
at.stop();
at.release();
}
私有无效开始记录()
{
记录=新的音频记录(MediaRecorder.AudioSource.MIC、sampleRate、,
channelConfig、audioFormat、BufferSize);
if(AudioRecord.STATE_INITIALIZED==record.getState())
record.startRecording();
isRecording=true;
/*运行一个线程进行录制*/
recordingThread=新线程(new Runnable()){
@凌驾
公开募捐{
WriteeAudioDataToFile();
}
}“录音机线程”);
recordingThread.start();
线程=新线程(新可运行(){
公开募捐{
while(thread!=null&&!thread.isInterrupted()){
//让我们让线程在大约采样时间内休眠一段时间
试一试{
Thread.sleep(SAMPLE_DELAY)}catch(InterruptedException ie){ie.printStackTrace();}
readAudioBuffer();//调用后,我们可以获得分配给lastLevel变量的最后一个值
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
如果(lastLevel>=7&&lastLevel 50&&lastLevel 100&&lastLevel 170){
text.setText(String.valueOf(lastLevel));
setTextColor(getResources().getColor(R.color.Blue));
布局.背景颜色(颜色.白色);
储油罐。设置图像资源(R.可提取。qtank);
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
}
});
}
}
}“录音机线程”);
thread.start();
}
私有void writeeAudioDataToFile()
{
字节数据[]=新字节[BufferSize];
/*将音频录制到以下文件*/
字符串filePath=“/sdcard/recorded.pcm”;
filename=Environment.getExternalStorageDirectory().getAbsolutePath();
文件名+=“/audiofile.pcm”;
FileOutputStream os=null;
试一试{
os=新的FileOutputStream(filePath);
}