如何使用Spring Boot串流音频 [英] How to stream audio with spring boot

查看:785
本文介绍了如何使用Spring Boot串流音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让用户播放声音.我的实现与firefox正常工作.在Safari上不会播放声音.我确认,音频控件可与其他网站一起在野生动物园中使用.因此,我认为我必须在控制器中进行某些更改?

I want to enable the user to play a sound. My implementation works fine with firefox. On Safari the sound is not played. I verified, that the audio control works in safari with other websites. So, I assume, that I will have to change something in my controller?

控制器:

@RequestMapping(value = "/sound/character/get/{characterId}", method = RequestMethod.GET, produces = {
            MediaType.APPLICATION_OCTET_STREAM_VALUE })
        public ResponseEntity playAudio(HttpServletRequest request,HttpServletResponse response, @PathVariable("characterId") int characterId) throws FileNotFoundException{

        logger.debug("[downloadRecipientFile]");

        de.tki.chinese.entity.Character character = characterRepository.findById(characterId);
        String file = UPLOADED_FOLDER + character.getSoundFile();

        long length = new File(file).length();


        InputStreamResource inputStreamResource = new InputStreamResource( new FileInputStream(file));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentLength(length);
        httpHeaders.setCacheControl(CacheControl.noCache().getHeaderValue());
        return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
    }

查看

        <audio id="voice" controls="">
            <source src="/sound/character/get/2">
        </audio>

Firefox(工作正常):

Firefox (works fine):

Safari(不起作用):

Safari (not working):

推荐答案

大多数播放器将需要一个支持部分内容请求(或字节范围)的控制器.

Most players are going to require a controller that supports partial content requests (or byte ranges).

实现起来可能有些棘手,所以我建议使用类似Spring Community Project的东西 Spring内容,那么您完全不必担心如何实现控制器.从概念上看,概念和编程模型与Spring Data的非常相似,您已经在使用它们.

This can be a little tricky to implement so I would suggest using something like the Spring Community Project Spring Content then you don't need to worry about how to implement the controller at all. The concepts and programming model are very similar to Spring Data's that, by looks of it, you are already using.

假设您使用的是Spring Boot(如果您不使用Spring Boot,请告诉我),那么它将看起来像这样:

Assuming you are using Spring Boot (let me know if you are not) then it would look something like this:

pom.xml

pom.xml

<!-- Java API -->
<dependency>
    <groupId>com.github.paulcwarren</groupId>
    <artifactId>content-fs-spring-boot-starter</artifactId>
    <version>0.6.0</version>
</dependency>
<!-- REST API -->
<dependency>
    <groupId>com.github.paulcwarren</groupId>
    <artifactId>spring-content-rest-boot-starter</artifactId>
    <version>0.6.0</version>
</dependency>

SpringBootApplication.java

SpringBootApplication.java

@SpringBootApplication
public class YourSpringBootApplication {

  public static void main(String[] args) {
    SpringApplication.run(YourSpringBootApplication.class, args);
  }

  @Configuration
  @EnableFilesystemStores
  public static class StorageConfig {
    File filesystemRoot() {
        return new File("/path/to/your/sounds");
    }

    @Bean
    public FileSystemResourceLoader fsResourceLoader() throws Exception {
      return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
    }
  }

  @StoreRestResource(path="characterSounds")
  public interface SoundsContentStore extends ContentStore<UUUID,String> {
    //
  }
}

Charater.java

Charater.java

public class Character {

    @Id
    @GeneratedValue
    private Long id;

    ...other existing fields...

    @ContentId
    private UUID contentId;

    @ContentLength
    private Long contnetLength;

    @MimeType
    private String mimeType;
} 

这就是在/characterSounds创建支持流的基于REST的音频服务所需要的全部.实际上,它也支持完整的CRUD功能.创建== POST,读取== GET(包括所需的字节范围支持),更新== PUT,删除== DELETE(如果对您有用).上传的声音将存储在"/path/to/your/sounds"中.

This is all you need to create a REST-based audio service at /characterSounds supporting streaming. It actually supports full CRUD functionality as well; Create == POST, Read == GET (include the byte-range support that you need), Update == PUT, Delete == DELETE in case that is useful to you. Uploaded sounds will be stored in "/path/to/your/sounds".

所以...

GET /characterSounds/{characterId}

将返回部分内容响应,并且应该在大多数(如果不是全部)播放器中正确播放(包括向前和向后搜索).

will return a partial content response and this should stream properly in most, if not all, players (including seeking forwards and backwards).

HTH

这篇关于如何使用Spring Boot串流音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆