0

I have a problem with playing music. It doesnt play. I want to play music by clicking on the button.

<script>
  $(document).ready(function() {
    $('.button').submit(function() {
      var audio = document.getElementById('audioFile');
      audio.play();
    });
  });
</script>
</head>

<body>
  <audio id="audioFile">
    <source src="font/sound.mp3" type="audio/mpeg">
  </audio>
  <div class="inputMessage">

    <form method="POST" action="/index.php">
      <textarea class="chatMessage" name="text" placeholder="Текст сообщения"></textarea>
      <br>
      <input class="button" type="submit" name="enter" value="Отправить">
      <input type="reset" value="Очистить">
    </form>
  </div>
</body>
Catalina
  • 95
  • 2
  • 12
  • Try with this solution :http://stackoverflow.com/a/18628124/2815635 – Niklesh Raut Jun 10 '16 at 11:05
  • What error message do you see? What does debugging show? – Michael Green Jun 10 '16 at 11:05
  • I need to send text from textarea and when I click on the buttom, I should hear a sound – Catalina Jun 10 '16 at 11:07
  • `document.getElementById('audioFile');` does not point to `src` attribute in `soruce` tag. Try to change the reference. And when you have jquery , why using JavaScript code to get the element attributes ?? – Sameer K Jun 10 '16 at 11:10
  • I really dont know how to debug, but in log i can see nothing – Catalina Jun 10 '16 at 11:10
  • i was trying do it like this: $('.button').click(function() { var audio = new Audio(); audio.src("font/sound.mp3"); audio.autoplay(); }); – Catalina Jun 10 '16 at 11:12
  • check this `http://stackoverflow.com/questions/8489710/play-an-audio-file-using-jquery-when-a-button-is-clicked``. – Sameer K Jun 10 '16 at 11:14
  • Why the downvote? Because they used the php tag? – Bulrush Jun 10 '16 at 11:21
  • @Bulrush don't ask. Everything seems to get randomly downvoted all the time. – Jeremy Thille Jun 10 '16 at 11:40
  • I've put a php tag, because in my code in the top side of the file i have php code for work with POST method. I've removed that part of code, but forgot to remove php tag :) – Catalina Jun 10 '16 at 14:47
  • http://stackoverflow.com/questions/8489710/play-an-audio-file-using-jquery-when-a-button-is-clicked i'm trying to fix it with this prompt. – Catalina Jun 10 '16 at 14:47

1 Answers1

2

First thing: .submit() method exists on forms, not inputs. You can use .click() method instead. Second thing: when you click your button the form is sent and page redirects to /index.php. To make playing sound possible you have to stay at the same page (request can still be send asynchronously). Here is the way to prevent loading new page:

$('.button').click(function(ev) { // jQuery passes the event as a parameter
  var audio = document.getElementById('audioFile');
  audio.play();
  ev.preventDefault(); // and we prevent the form from being sent
});

Take a look at demo: https://jsfiddle.net/s48jcrvc/1/

Daniel Kucal
  • 8,684
  • 6
  • 39
  • 64