In today's digital landscape, delivering multimedia content efficiently is crucial.
Whether you're building a music platform, a podcast app, or any service involving audio playback, streaming audio files directly from storage can enhance user experience by reducing latency and conserving bandwidth. This article guides you through streaming audio files stored in MinIO using Spring Boot, ensuring seamless playback without the need for downloads.
Understanding the Basics
MinIO is an open-source, high-performance object storage system compatible with Amazon S3 APIs. It's designed for storing unstructured data like photos, videos, and audio files.Spring Boot is a Java-based framework that simplifies the development of stand-alone, production-grade applications. Its robust ecosystem and ease of integration make it a popular choice for building RESTful services.Setting Up MinIO
Before diving into the code, ensure MinIO is up and running:
- Download and Install MinIO:
- Start MinIO Server:
- Run the following command to start the server:
minio server /data
- Access MinIO Console:
- Navigate to
http://localhost:9000
in your browser.
- Use the default credentials:
- Username: minioadmin
- Password: minioadmin
- Create a Bucket:
- In the MinIO console, create a new bucket (e.g.,
audio-files
) to store your audio content.Medium
Integrating MinIO with Spring Boot
1. Add Dependencies:
Include the MinIO client library in your
pom.xml
:
<dependency>
<groupId>io.minio</groupId>
<artifactId>>minio</artifactId>
<version>8.3.4</version>
</dependency>
2. Configure MinIO Properties:
In your
application.properties
or
application.yml
, add:
minio.url=http://localhost:9000
minio.access-key=minioadmin
minio.secret-key=minioadmin
minio.bucket-name=audio-files
3. Create MinIO Configuration Class:
Set up a configuration class to initialize the MinIO client:
@Configuration
public class MinioConfig {
@Value("${minio.url}")
private String minioUrl;
@Value("${minio.access-key}")
private String accessKey;
@Value("${minio.secret-key}")
private String secretKey;
@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(minioUrl)
.credentials(accessKey, secretKey)
.build();
}
}
Streaming Audio Files
1. Implement the Controller:
Create a REST controller to handle streaming requests:
@RestController
@RequestMapping("/audio")
public class AudioStreamController {
@Autowired
private MinioClient minioClient;
@Value("${minio.bucket-name}")
private String bucketName;
@GetMapping("/stream/{filename}")
public void streamAudio(@PathVariable String filename, HttpServletResponse response) {
try {
InputStream inputStream = minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(filename)
.build()
);
response.setContentType("audio/mpeg");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
}
2. Handle Byte Range Requests (Optional):
To support seeking within audio files, implement byte-range handling:
@GetMapping("/stream/{filename}")
public ResponseEntity<Resource> streamAudio(@PathVariable String filename, @RequestHeader HttpHeaders headers) {
try {
InputStream inputStream = minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(filename)
.build()
);
byte[] bytes = IOUtils.toByteArray(inputStream);
ByteArrayResource resource = new ByteArrayResource(bytes);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.setContentLength(bytes.length);
return new ResponseEntity<>(resource, responseHeaders, HttpStatus.PARTIAL_CONTENT);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
Frontend Integration
In your frontend application, use the HTML5
<audio>
tag to play the streamed audio:
<audio controls>
<source src="http://localhost:8080/audio/stream/sample.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
This setup allows users to play audio files directly from your application without downloading them, providing a seamless listening experience.
image quote pre code