Owen Osborn
Owen Osborn

Reputation: 23

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). 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. (at least in Chrome and FireFox, Safari seems to continue working).

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. Does this look like the correct approach, or am I missing something?

Upvotes: 2

Views: 1706

Answers (1)

L. C
L. C

Reputation: 106

You can change the expiration time for active storage like this

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

Upvotes: 1

Related Questions