What is the process of adjusting the volume in Shiny using Javascript?

I've been attempting to adjust the volume of an audio tag within my Shiny app. While some resources suggest using the "volume" argument directly within the audio tag, I haven't had success in implementing this.

After stumbling upon this page https://www.w3schools.com/jsref/prop_audio_volume.asp as well as this interactive example https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_audio_volume, it seems that Javascript is utilized to modify the volume. However, I'm facing challenges in understanding how to incorporate a Javascript function inside a Shiny application. Any assistance on this matter would be greatly appreciated.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  tags$audio(id = "myAudio", controls = NA, autoplay = NA, tags$source(src="aud.mpeg")),
  br(),
  actionButton("mybutton", "Submit"),

  tags$script('
    var x = document.getElementById("myAudio").onclick 
    function setHalfVolume() {
      x.volume = 0.2;
    };
  ')
)

server <- function(input, output) {
  observeEvent(input$mybutton, {
    setHalfVolume()
  })

}

shinyApp(ui = ui, server = server)

Answer №1

You are on the verge of reaching your goal, but encountering some issues with obtaining the correct ids.

To stay on course, replace the current script with:

document.getElementById("mybutton").onclick = 
    function adjustVolume() {
        document.getElementById("myAudio").volume = 0.2;
    };

Note that the onclick attribute of the button needs to be modified, not the attribute of the audio element. The volume attribute within the audio DOM should be adjusted.

Alternatively, you could directly utilize the onclick attribute of the actionButton.

tags$script('
    decrease = function(){ document.getElementById("myAudio").volume = 0.2;}
')
tags$audio(id = "myAudio", controls = NA, autoplay = NA,     tags$source(src="sound.mp3")),
actionButton("lowerButton", "lower", onclick="decrease()")

Answer №2

I wanted to extend my gratitude for the question and feedback provided. It has proven to be quite enlightening. Following up, I was curious about the possibility of adjusting the volume using a slider. This would involve incorporating an input variable into the script. Here's an attempt at achieving this functionality:

tags$script('volumeAdjustment = function(input){ document.getElementById("myAudio").volume = input;}'),
#slider for adjusting volume level
sliderInput("levelSlider", "Volume Level:", min = 0, max = 1, value = 0.4),
#button to adjust volume level
actionButton("adjustButton", "Adjust Volume", onclick=paste0("volumeAdjustment(","levelSlider$value",")")),

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

What is the best way to incorporate an input id value (based on iteration) into a while loop that points to a specific piece of html located outside of the loop

In my scenario, I need to dynamically add input fields to a form based on the selection made in a dropdown. The issue arises when these new input fields end up sharing the same ID, which is causing problems in the code. To resolve this, I am looking to app ...

If I were to utilize my own Threejs canvas,Rephrased

Currently, I'm facing an issue while trying to showcase a globe using Three.js. Everything works perfectly until I attempt to use my own canvas. It seems that when I place my canvas before the JavaScript file in the HTML structure, it doesn't dis ...

delivering json replies with abundant data

I am facing an issue where the data sent to my view does not correspond to the data generated by the query. Only a single data entry appears. Here is the function in question: function lokasi_ajax() { var kode_lokasi = $('#kode_lokasi').val() ...

Find the similarities and differences between two circular structured JSON objects

How can I effectively compare 2 websocket connections on my nodejs webserver when I can't simply use json.stringify due to the circular structure of the objects? ...

Improved method for detecting click events

I am facing an issue with two calendars controlled by user input. Currently, if a user clicks to open one calendar and then clicks anywhere outside of it, both calendars close simultaneously because they are detecting each other as the target. I am looking ...

Problems with Ajax functionality in CodePen

Currently working on the Wikipedia Viewer project for freeCodeCamp. I'm encountering an issue with the ajax function as nothing is being logged in the console upon click. The code snippet in question is provided below. Appreciate any help or insight o ...

issues experienced when attempting to loop with fastLink

Apologies for any language discrepancies as I am utilizing Google Translate. I have two dataframes that I am applying fastlink::fastLink() to. df1<-data.frame(col1=c("testA","testA","testA","testB","testB&qu ...

Issue with PHP Upload: Index is undefined

Having Trouble with PHP Upload: Encountered an issue: Undefined index: file in Error on line: $count = count($_FILES['file']['name']); Tried numerous codes to fix this error, but none have worked so far PHP Code: <?php $count ...

Create a ggplot2 heatmap with distinct colors for values that exceed or fall below specified thresholds

When creating a table with highlighted cells based on their Perc_Diff values, I want to implement a scale_fill_gradient2 pattern for values between -100 and +100. However, for values <= -100, I want the cells to be blue, and for values >= 100, I want ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

Having trouble retrieving the table value from an HTML document?

I am trying to retrieve specific information from this source: https://i.sstatic.net/g1wDj.png This information is crucial for fetching data from a database using a primary key. However, extracting this value has proven to be quite challenging. Upon docu ...

Encountering a Issue in Transmitting Data from Laravel Controller to Ajax using Jquery GET Method with

Currently, I am utilizing Laravel 5.4 as the Backend server technology. Below is the Controller code snippet from my Backend: $locations = Neighborhood::where('House_id', $id)->get(); $json = json_encode($locations); return respon ...

What is the best method for ensuring a user remains logged in even after their access token expires, requiring them to log in again to resume their normal

Currently utilizing the Nuxt-axios module alongside a proxy. Implemented common error handling code in Plugins/axios.js export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) { $axios.onRequest(config => { i ...

What is the process for retrieving the data from the POST request body on the client side?

Greetings to all, I am a student who is still in the process of learning and have a question about passing data from server to client. Currently, I have an Arduino sensor that sends POST requests containing sensor data to an express server. The server suc ...

Encountering an issue with Angular directive attributes

I am attempting to create an angular directive that will extract a substring from a passed-in attribute. Below is the code I have written: HTML: <body ng-controller="MainCtrl"> <div><substring message="This is a test."></substri ...

Refresh a gif animation when the page is reloaded

I have a website that features a div with a dynamic gif image as the background. The gif animation is set to play only on the initial page load. However, if the page is refreshed or navigated back to the homepage from another page, the animation does not ...

1. Common obstacles in the functionality of data binding2. Constraints

Working on a basic controller to perform some calculations, which is a simplified version of a more complex project. The issue I'm facing is that the result displayed in the HTML gets recalculated every time there's a change, but when calculating ...

What is the best way to send data between pages in a React application?

After solving the question, I can confirm that the code lines are correct. By utilizing console log, I verified that all parameters are being passed correctly: I am creating a website to showcase my personal projects, using components across different pag ...

Encountering a 500 Internal Server Error message while attempting to access a WebMethod through ajax

I'm encountering an issue with accessing my C# WebMethod in the code behind, resulting in a 500 internal server error. I cannot figure out why it's not working, so any assistance in identifying the problem would be highly appreciated. https://i. ...