/** * make sine wave humble MediaAudio. * * @return */ private MediaAudio beepSamples() { int sampleRate = 44100; // 44.1KHz int sampleNum = 44100; // 44100 samples(1sec) int channel = 2; // 2channel(stereo) int tone = 440; // 440Hz tone. int bit = 16; // 16bit ByteBuffer buffer = ByteBuffer.allocate((int) sampleNum * bit * channel / 8); double rad = tone * 2 * Math.PI / sampleRate; // radian for each sample. double max = (1 << (bit - 2)) - 1; // ampletude buffer.order(ByteOrder.LITTLE_ENDIAN); for (int i = 0; i < sampleNum; i++) { short data = (short) (Math.sin(rad * i) * max); for (int j = 0; j < channel; j++) { buffer.putShort(data); } } buffer.flip(); logger.info("data size for 1sec buffer.:" + buffer.remaining()); MediaAudio samples = MediaAudio.make( sampleNum, sampleRate, channel, Layout.CH_LAYOUT_STEREO, Type.SAMPLE_FMT_S16); samples.getData(0).put(buffer.array(), 0, 0, buffer.remaining()); logger.info( "{}", samples.getDataPlaneSize(0)); // why this size is little bit bigger than original buffer? samples.setComplete(true); samples.setTimeBase(Rational.make(1, 44100)); samples.setTimeStamp(0); samples.setNumSamples(sampleNum); return samples; }
private void processConvert(Muxer muxer, Encoder encoder) throws Exception { muxer.open(null, null); MediaPacket packet = MediaPacket.make(); MediaAudio samples = beepSamples(); logger.info(samples.toString()); if (samples.getSampleRate() != encoder.getSampleRate() || samples.getFormat() != encoder.getSampleFormat() || samples.getChannelLayout() != encoder.getChannelLayout()) { final MediaAudioResampler resampler = MediaAudioResampler.make( encoder.getChannelLayout(), encoder.getSampleRate(), encoder.getSampleFormat(), samples.getChannelLayout(), samples.getSampleRate(), samples.getFormat()); resampler.open(); MediaAudio spl = MediaAudio.make( samples.getNumSamples(), encoder.getSampleRate(), encoder.getChannels(), encoder.getChannelLayout(), encoder.getSampleFormat()); resampler.resample(spl, samples); logger.info(spl.toString()); logger.info("{}", spl.getNumSamples()); Assert.assertEquals(spl.getNumSamples(), samples.getNumSamples()); samples = spl; } logger.info(samples.toString()); // we only have one set of samples. encoder.encodeAudio(packet, samples); logger.info("{}", packet); if (packet.isComplete()) muxer.write(packet, false); // Flush the encoders do { encoder.encodeAudio(packet, null); logger.info("{}", packet); if (packet.isComplete()) { muxer.write(packet, false); } } while (packet.isComplete()); muxer.close(); }