5
Tôi cố gắng để theo liên kết này:Mix âm thanh trong android
Nhưng sau khi trộn các file âm thanh, tập tin (mixed.wav) trên sdcard không thể được chơi, tôi làm không biết tại sao. Bạn có thể giúp tôi không ?. Thank you very much ..
mã của tôi này:
public class MainActivity mở rộng Hoạt động {
public static final int FREQUENCY = 44100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mixSound();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void mixSound() throws IOException {
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, 44100, AudioTrack.MODE_STREAM);
InputStream in1 = getResources().openRawResource(R.raw.media_b);
InputStream in2 = getResources().openRawResource(R.raw.media_c);
byte[] arrayMusic1 = null;
arrayMusic1 = new byte[in1.available()];
arrayMusic1 = createMusicArray(in1);
in1.close();
byte[] arrayMusic2 = null;
arrayMusic2 = new byte[in2.available()];
arrayMusic2 = createMusicArray(in2);
in2.close();
byte[] output = new byte[arrayMusic1.length];
audioTrack.play();
for (int i = 0; i < output.length; i++) {
float samplef1 = arrayMusic1[i]/128.0f;
float samplef2 = arrayMusic2[i]/128.0f;
float mixed = samplef1 + samplef2;
// reduce the volume a bit:
mixed *= 0.8;
// hard clipping
if (mixed > 1.0f) mixed = 1.0f;
if (mixed < -1.0f) mixed = -1.0f;
byte outputSample = (byte) (mixed * 128.0f);
output[i] = outputSample;
}
audioTrack.write(output, 0, output.length);
convertByteToFile(output);
}
public static byte[] createMusicArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling function
}
public static void convertByteToFile(byte[] fileBytes) throws FileNotFoundException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/mixed.wav"));
try {
bos.write(fileBytes);
bos.flush();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Cách khắc phục, tôi không biết làm cách nào. Bạn có thể giúp tôi không? Cảm ơn bạn rất nhiều :) –
Bạn viết tất cả các trường được chỉ định trong tiêu đề. Đầu tiên chuỗi 'RIFF', sau đó giá trị 32 bit chứa '36 + size_of_your_audio_data', sau đó là chuỗi' WAVE', v.v. – Michael
Cảm ơn bạn rất nhiều. Tôi đã thành công lẫn lộn. Nhưng tập tin mixed.wav với tiếng ồn. Làm thế nào để sửa chữa nó, loại bỏ tiếng ồn trắng. Tôi phải làm gì với mảng byte wav của mình. Bạn có thể giúp tôi được không? –