2

My web page includes a bunch of links that are generated via php. These are links to mp3 files, and right now when I click on them the sound starts playing in a new tab. How can I add a script so that all links start playing the source sound directly in the same tab when clicked (and stop when re-clicked)? Apologies in advance for a possibly stupid question, but please have mercy as I am very new to all of these things.

<a href="url1" target="_blank">value1</a>
<a href="url2" target="_blank">value2</a>
<a href="url3" target="_blank">value3</a>
CHRD
  • 1,917
  • 1
  • 15
  • 38
  • You'll need to use an `audio` element like the answer below suggests, however there is much more logic required if you want to dynamically switch the `src` of that `audio`. See the duplicate I marked for example code. – Rory McCrossan Jun 06 '19 at 10:33
  • Ok thanks I'll take a look for sure! :) – CHRD Jun 06 '19 at 10:34

1 Answers1

1

You should be using an audio tag like the following:

<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>

Read more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/

Also, the target="_blank" attribute will cause the link to open in a new tab.

Good luck on your coding journey!

yosefc
  • 60
  • 8
  • 2
    Thanks! Wouldn't this bring up the audio player controls? I just want the link text, e.g. "value1" to act as a play/stop button. – CHRD Jun 06 '19 at 10:18
  • It would, but it's better as far as accessibility goes. If you still want to use an a tag then just remove the target="_blank" – yosefc Jun 06 '19 at 10:21
  • 1
    OK I see I might have misformulated the question. I don't want the page to change, removing the `target="_blank"` would load the page where the audio is located. I want to stay on the same page. – CHRD Jun 06 '19 at 10:24
  • So then you must use an audio tag.. – yosefc Jun 06 '19 at 10:28
  • you can get rid of the controls by removing the "controls" attribute from the audio tag. then you can make the audio played on click event of the link, see [this question](https://stackoverflow.com/questions/27368778/how-to-toggle-audio-play-pause-with-one-button-or-link) – Noam Jun 06 '19 at 10:32