Created
October 7, 2021 14:32
-
-
Save Fosol/7410a13f7c23769c857119813a09cc0a to your computer and use it in GitHub Desktop.
Java - Audio/Video Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original source [link](https://medium.com/tekraze/convert-video-to-another-format-in-spring-boot-java-based-apps-7763fbc4d7ce) | |
Maven Config | |
```xml | |
<dependency> | |
<groupId>ws.schild</groupId> | |
<artifactId>jave-core</artifactId> | |
<version>2.7.1</version> | |
</dependency> | |
# Linux 64 bit based | |
<dependency> | |
<groupId>ws.schild</groupId> | |
<artifactId>jave-nativebin-linux64</artifactId> | |
<version>2.7.1</version> | |
</dependency> | |
# Windows 64 bit based | |
<dependency> | |
<groupId>ws.schild</groupId> | |
<artifactId>jave-nativebin-win64</artifactId> | |
<version>2.7.1</version> | |
</dependency> | |
# Mac OS 64 bit based | |
<dependency> | |
<groupId>ws.schild</groupId> | |
<artifactId>jave-nativebin-osx64</artifactId> | |
<version>2.7.1</version> | |
</dependency> | |
``` | |
Code Sample | |
```java | |
Convert a video to Mp4(MPEG-4 AVC) and AAC audio | |
/* Step 1. Declaring source file and Target file */ | |
File source = new File("source.avi"); | |
File target = new File("target.mp4"); | |
/* Step 2. Set Audio Attrributes for conversion*/ | |
AudioAttributes audio = new AudioAttributes(); | |
audio.setCodec("aac"); | |
// here 64kbit/s is 64000 | |
audio.setBitRate(64000); | |
audio.setChannels(2); | |
audio.setSamplingRate(44100); | |
/* Step 3. Set Video Attributes for conversion*/ | |
VideoAttributes video = new VideoAttributes(); | |
video.setCodec("h264"); | |
video.setX264Profile(X264_PROFILE.BASELINE); | |
// Here 160 kbps video is 160000 | |
video.setBitRate(160000); | |
// More the frames more quality and size, but keep it low based on devices like mobile | |
video.setFrameRate(15); | |
video.setSize(new VideoSize(400, 300)); | |
/* Step 4. Set Encoding Attributes*/ | |
EncodingAttributes attrs = new EncodingAttributes(); | |
attrs.setFormat("mp4"); | |
attrs.setAudioAttributes(audio); | |
attrs.setVideoAttributes(video); | |
/* Step 5. Do the Encoding*/ | |
try { | |
Encoder encoder = new Encoder(); | |
encoder.encode(source, target, attrs); | |
} catch (Exception e) { | |
/*Handle here the video failure*/ | |
e.printStackTrace(); | |
} | |
``` | |
If not converting video, leave out line 61 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment