0

I Want To Play Audio File On File Selected

Can AnyOne Help Me.

<input type="file" name="fileAudio" value="" />

<audio controls="controls" id="audioPreview">
      <source src="" type="audio/mp4" />
</audio>
  • 1
    Possible duplicate of [Play audio local file with html](https://stackoverflow.com/questions/38265242/play-audio-local-file-with-html) – zer00ne Feb 27 '19 at 07:05

1 Answers1

1

Incidentally, I recently needed such a method and got this solution

It's simple. Just need to set up a method when changing the file.

Html:

<input type="file" name="fileAudio" value="" onchange="PreviewAudio(this, $('#audioPreview'))" />

<audio controls="controls" id="audioPreview" style="display:none">
      <source src="" type="audio/mp4" />
</audio>

Javascript:

function PreviewAudio(inputFile, previewElement) {

    if (inputFile.files && inputFile.files[0] && $(previewElement).length > 0) {

        $(previewElement).stop();

        var reader = new FileReader();

        reader.onload = function (e) {

            $(previewElement).attr('src', e.target.result);
            var playResult = $(previewElement).get(0).play();

            if (playResult !== undefined) {
                playResult.then(_ => {
                    // Automatic playback started!
                    // Show playing UI.

                    $(previewElement).show();
                })
                    .catch(error => {
                        // Auto-play was prevented
                        // Show paused UI.

            $(previewElement).hide();
                        alert("File Is Not Valid Media File");
                    });
            }
        };

        reader.readAsDataURL(inputFile.files[0]);
    }
    else {
        $(previewElement).attr('src', '');
        $(previewElement).hide();
        alert("File Not Selected");
    }
}