简体   繁体   English

如何播放从Rails / Active Storage提供的音频文件

[英]How to play audio files served from Rails / Active Storage

I have a model that accepts audio file uploads (using Rails 5.2.2, active_storage). 我有一个接受音频文件上传的模型(使用Rails 5.2.2,active_storage)。 To test things out I made a view that simply creates a play button for each one: 为了测试,我创建了一个视图,该视图仅为每个视图创建一个播放按钮:

<% @page.uploads.each do |upload| %>
    <div class="player btn btn-outline-secondary">
        <%= audio_tag rails_blob_url upload %>
        Play
    </div>
<% end %>

<script>  
$(document).ready(function() {
    $(".player").click(function() {
        $(this).children('audio')[0].play();
    });
});          
</script>

This works great, but after 5 minutes it stops working, hitting the buttons no longer play the sounds and page must be refreshed to work again. 效果很好,但是5分钟后它停止工作,按一下按钮将不再播放声音,必须刷新页面才能再次工作。 (at least in Chrome and FireFox, Safari seems to continue working). (至少在Chrome和FireFox中,Safari似乎可以继续工作)。

I think it has something to do with the redirect URLs generated by active storage expiring after 5 minutes... but I thought the rails_blob_url always returned a fresh URL to the file. 我认为这与活动存储在5分钟后过期后生成的重定向URL有关...但是我认为rails_blob_url总是向文件返回新的URL。 Does this look like the correct approach, or am I missing something? 这看起来像是正确的方法,还是我错过了什么?

You can change the expiration time for active storage like this 您可以这样更改活动存储的到期时间

# config/initializers/active_storage.rb
ActiveStorage::Service.url_expires_in = 1.hour

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM