skip to Main Content

I have 3 files.

First one is audios, including some audios, audios.

Second one is index.html, nothing here, shown as below.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>

    </body>
</html>

The last one is player folder, it’s a music player app,
music player

What I want to do is that, first I open index.html, (index.html should have some links), for example, when I click one link, it should direct to player.html and start to play the corresponding music.

What confused me is that, how player.html know which music it should play?
I initiallly used

<a href="audios/20230119.mp3">20230119</a>

It did start to play 20230119.mp3, but it’s the default music player, not the one I built.

One idea is that maybe index.html should send some messages (ex.the song’s name) to player.html, but what skills I should learn and use?

I used

<a href=""></a>

but this won’t give me the result I want.

2

Answers


  1. The index.html and player.html pages are typically served by a web server, and can communicate with each other using various techniques. One common way to send messages from index.html to player.html is by using a web socket connection.

    A web socket connection allows real-time, bidirectional communication between the web server and the client’s web browser. The server can send messages to the client using the web socket, and the client can respond with messages of its own.

    To set up a web socket connection, you would typically use a JavaScript library such as Socket.IO, which provides a simple API for sending and receiving messages over web sockets. Once the connection is established, you can send messages between the index.html and player.html pages by using the API provided by the library.

    Login or Signup to reply.
  2. Well a solution would be something like this.

    You’ll need to create a link pointing to the player.html with a parameter in the url to specify the name of the file.

    <a href="player?name=something">something</a>
    

    Then in your player.html file, you’ll need to retreive the name attribute in the url with JS.

    In your head section, you can insert this script :

    <script>
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const name = urlParams.get('name');
    </script>
    

    Then with the name retreived from the URL, you can use an HTMLAudioElement to launch the audio file.

    Something like this :

    const audioElement = new Audio(`audios/${name}.mp3`);
    audioElement.play();
    

    Have a lovely day,

    Sources :
    https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement
    https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search