
Recherche avancée
Médias (91)
-
Spoon - Revenge !
15 septembre 2011, par
Mis à jour : Septembre 2011
Langue : English
Type : Audio
-
My Morning Jacket - One Big Holiday
15 septembre 2011, par
Mis à jour : Septembre 2011
Langue : English
Type : Audio
-
Zap Mama - Wadidyusay ?
15 septembre 2011, par
Mis à jour : Septembre 2011
Langue : English
Type : Audio
-
David Byrne - My Fair Lady
15 septembre 2011, par
Mis à jour : Septembre 2011
Langue : English
Type : Audio
-
Beastie Boys - Now Get Busy
15 septembre 2011, par
Mis à jour : Septembre 2011
Langue : English
Type : Audio
-
Granite de l’Aber Ildut
9 septembre 2011, par
Mis à jour : Septembre 2011
Langue : français
Type : Texte
Autres articles (89)
-
Gestion des droits de création et d’édition des objets
8 février 2011, parPar défaut, beaucoup de fonctionnalités sont limitées aux administrateurs mais restent configurables indépendamment pour modifier leur statut minimal d’utilisation notamment : la rédaction de contenus sur le site modifiables dans la gestion des templates de formulaires ; l’ajout de notes aux articles ; l’ajout de légendes et d’annotations sur les images ;
-
Contribute to documentation
13 avril 2011Documentation is vital to the development of improved technical capabilities.
MediaSPIP welcomes documentation by users as well as developers - including : critique of existing features and functions articles contributed by developers, administrators, content producers and editors screenshots to illustrate the above translations of existing documentation into other languages
To contribute, register to the project users’ mailing (...) -
Submit bugs and patches
13 avril 2011Unfortunately a software is never perfect.
If you think you have found a bug, report it using our ticket system. Please to help us to fix it by providing the following information : the browser you are using, including the exact version as precise an explanation as possible of the problem if possible, the steps taken resulting in the problem a link to the site / page in question
If you think you have solved the bug, fill in a ticket and attach to it a corrective patch.
You may also (...)
Sur d’autres sites (4638)
-
ffmpeg : problems playing video on android
25 novembre 2020, par Jonathan García(Translated) Hello ! I have the following problem. I concatenate multiple ts files and convert to mp4 with ffmpeg. I do this operation multiple times in an automated way, so I don't always check the results, but whenever I do, on the computer, the result obtained is as expected. However, some videos, when played on an Android device, are seen incorrectly in any application : Chrome, Firefox, Vlc, etc. The version of ffmpeg I use is the latest. This is the command I use :


ffmpeg.exe -hwaccel dxva2 -y -f concat -i list.txt -acodec copy -vcodec copy output.mp4 -preset normal


Results :






This is the output of ffmpeg :


ffmpeg version n4.3.1-26-gca55240b8c Copyright (c) 2000-2020 the FFmpeg developers
 built with gcc 9.3-win32 (GCC) 20200320
 configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --disable-w32threads --enable-pthreads --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-opencl --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
 libavutil 56. 51.100 / 56. 51.100
 libavcodec 58. 91.100 / 58. 91.100
 libavformat 58. 45.100 / 58. 45.100
 libavdevice 58. 10.100 / 58. 10.100
 libavfilter 7. 85.100 / 7. 85.100
 libswscale 5. 7.100 / 5. 7.100
 libswresample 3. 7.100 / 3. 7.100
 libpostproc 55. 7.100 / 55. 7.100
Trailing option(s) found in the command: may be ignored.
Input #0, concat, from 'list.txt':
 Duration: N/A, start: 0.000000, bitrate: N/A
 Stream #0:0: Data: timed_id3 (ID3 / 0x20334449)
 Stream #0:1: Video: h264 (Main) ([27][0][0][0] / 0x001B), yuv420p(tv, unknown/bt470bg/unknown, progressive), 320x568, 29.50 fps, 29.50 tbr, 90k tbn, 180k tbc
 Stream #0:2: Audio: aac (LC) ([15][0][0][0] / 0x000F), 44100 Hz, mono, fltp, 64 kb/s
Output #0, mp4, to 'output.mp4':
 Metadata:
 encoder : Lavf58.45.100
 Stream #0:0: Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, unknown/bt470bg/unknown, progressive), 320x568, q=2-31, 29.50 fps, 29.50 tbr, 90k tbn, 90k tbc
 Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 64 kb/s
Stream mapping:
 Stream #0:1 -> #0:0 (copy)
 Stream #0:2 -> #0:1 (copy)
Press [q] to stop, [?] for help
frame= 9504 fps=8330 q=-1.0 Lsize= 24561kB time=00:07:42.26 bitrate= 435.3kbits/s speed= 405x
video:21200kB audio:3100kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 1.073735%



Not all videos are "yuv420p (tv, unknown / bt470bg / unknown, progressive)", but this should not be the problem, since other videos with this information are seen correctly on Android.


To correct this type of video I do the following :


ffmpeg -y -f concat -i list.txt -c:v libx264 -preset slow -crf 22 -pix_fmt yuv420p -c:a aac -b:a 128k output.mp4


So I get the video to play correctly both on pc and Android. Unfortunately, automating the process by always using this last line occasionally causes problems (starting file 40MB, ending file> 1GB, more than 2 hours)


I would like, if possible, help me identify which videos will be viewed incorrectly on Android. Thank you very much in advance. Finally, this is the answer that ffmpeg gives when executing the line with which I fix the file :


ffmpeg version n4.3.1-26-gca55240b8c Copyright (c) 2000-2020 the FFmpeg developers
 built with gcc 9.3-win32 (GCC) 20200320
 configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --disable-w32threads --enable-pthreads --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-opencl --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
 libavutil 56. 51.100 / 56. 51.100
 libavcodec 58. 91.100 / 58. 91.100
 libavformat 58. 45.100 / 58. 45.100
 libavdevice 58. 10.100 / 58. 10.100
 libavfilter 7. 85.100 / 7. 85.100
 libswscale 5. 7.100 / 5. 7.100
 libswresample 3. 7.100 / 3. 7.100
 libpostproc 55. 7.100 / 55. 7.100
Input #0, concat, from 'list.txt':
 Duration: N/A, start: 0.000000, bitrate: N/A
 Stream #0:0: Data: timed_id3 (ID3 / 0x20334449)
 Stream #0:1: Video: h264 (Main) ([27][0][0][0] / 0x001B), yuv420p(tv, unknown/bt470bg/unknown, progressive), 320x568, 29.50 fps, 29.50 tbr, 90k tbn, 180k tbc
 Stream #0:2: Audio: aac (LC) ([15][0][0][0] / 0x000F), 44100 Hz, mono, fltp, 64 kb/s
Stream mapping:
 Stream #0:1 -> #0:0 (h264 (native) -> h264 (libx264))
 Stream #0:2 -> #0:1 (aac (native) -> aac (native))
Press [q] to stop, [?] for help
[libx264 @ 000001efdbaee540] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 000001efdbaee540] profile High, level 3.0, 4:2:0, 8-bit
[libx264 @ 000001efdbaee540] 264 - core 161 - H.264/MPEG-4 AVC codec - Copyleft 2003-2020 - http://www.videolan.org/x264.html - options: cabac=1 ref=5 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=8 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=2 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=12 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=3 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=50 rc=crf mbtree=1 crf=22.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'd.mp4':
 Metadata:
 encoder : Lavf58.45.100
 Stream #0:0: Video: h264 (libx264) (avc1 / 0x31637661), yuv420p, 320x568, q=-1--1, 29.50 fps, 15104 tbn, 29.50 tbc
 Metadata:
 encoder : Lavc58.91.100 libx264
 Side data:
 cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
 Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 128 kb/s
 Metadata:
 encoder : Lavc58.91.100 aac
More than 1000 frames duplicated 8960kB time=00:02:06.74 bitrate= 579.1kbits/s dup=999 drop=0 speed=15.7x
frame=13638 fps=468 q=-1.0 Lsize= 32033kB time=00:07:42.20 bitrate= 567.8kbits/s dup=4134 drop=0 speed=15.9x
video:25547kB audio:5995kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 1.557852%
[libx264 @ 000001efdbaee540] frame I:87 Avg QP:19.17 size: 12750
[libx264 @ 000001efdbaee540] frame P:4630 Avg QP:21.89 size: 4286
[libx264 @ 000001efdbaee540] frame B:8921 Avg QP:23.89 size: 583
[libx264 @ 000001efdbaee540] consecutive B-frames: 8.9% 8.6% 9.1% 73.4%
[libx264 @ 000001efdbaee540] mb I I16..4: 12.2% 76.2% 11.6%
[libx264 @ 000001efdbaee540] mb P I16..4: 3.7% 11.0% 0.8% P16..4: 37.1% 16.2% 5.7% 0.0% 0.0% skip:25.4%
[libx264 @ 000001efdbaee540] mb B I16..4: 0.3% 0.9% 0.1% B16..8: 30.4% 3.1% 0.3% direct: 0.8% skip:64.2% L0:51.4% L1:44.3% BI: 4.3%
[libx264 @ 000001efdbaee540] 8x8 transform intra:71.2% inter:66.8%
[libx264 @ 000001efdbaee540] direct mvs spatial:99.9% temporal:0.1%
[libx264 @ 000001efdbaee540] coded y,uvDC,uvAC intra: 52.5% 42.1% 5.5% inter: 9.7% 9.0% 0.3%
[libx264 @ 000001efdbaee540] i16 v,h,dc,p: 19% 21% 9% 50%
[libx264 @ 000001efdbaee540] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 22% 11% 13% 6% 9% 11% 9% 11% 8%
[libx264 @ 000001efdbaee540] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 23% 9% 8% 6% 14% 14% 11% 9% 6%
[libx264 @ 000001efdbaee540] i8c dc,h,v,p: 46% 20% 23% 12%
[libx264 @ 000001efdbaee540] Weighted P-Frames: Y:2.9% UV:0.8%
[libx264 @ 000001efdbaee540] ref P L0: 72.3% 12.2% 11.3% 2.1% 1.9% 0.2% 0.0%
[libx264 @ 000001efdbaee540] ref B L0: 93.1% 5.5% 1.1% 0.3%
[libx264 @ 000001efdbaee540] ref B L1: 97.6% 2.4%
[libx264 @ 000001efdbaee540] kb/s:452.67
[aac @ 000001efdbaee9c0] Qavg: 10682.834



-
Audio Video Mixing - Sync issue in Android with FFMPEG, Media Codec in different devices
24 novembre 2020, par khushbuI have already tried everything for Audio Video mixing and it's not working perfectly as in processing while mixing audio into the recorded video, sometimes the audio is ahead of video and vice-versa.


Using FFMPEG :


This is for add an Audio file to the Video file and generated the final Video where audio is replaced in the video.


val cmd ="-i $inputVideoPath -i ${inputAudio.absolutePath} -map 0:v -map 1:a -c:v copy -shortest ${outputVideo.absolutePath}"



After generating the final video, found some delay based on device performance so added delay in the below two cases :


1)Added delay in Audio if audio is ahead of the video.


val cmd = "-i ${tmpVideo.absolutePath} -itsoffset $hms -i ${tmpVideo.absolutePath} -map 0:v -map 1:a -c copy -preset veryfast ${createdVideo1?.absolutePath}"



2)Added delay in Video if the video is ahead of the audio.


val cmd = "-i ${tmpVideo.absolutePath} -itsoffset $hms -i ${tmpVideo.absolutePath} -map 1:v -map 0:a -c copy -preset veryfast ${createdVideo1?.absolutePath}"



NOTE : Here $hms is delay in 00:00:00.000 formate


but still, it's not working on all the devices like readmi, oneplus etc.


Using Media Codec :


Found some better performance in this solution but still not working on all the devices.


In this process, It's supporting .aac format so first if the user selected .mp3 formate than i have to convert it into .aac format using the below function :


fun Convert_Mp3_to_acc() {

 
 AndroidAudioConverter.load(requireActivity(), object : ILoadCallback {
 override fun onSuccess() {

 val callback: IConvertCallback = object : IConvertCallback {
 override fun onSuccess(convertedFile: File) {
 toggleLoader(false)
 audioLink = convertedFile.absolutePath
 append()
 

 }

 override fun onFailure(error: java.lang.Exception) {
 toggleLoader(false)
 Toast.makeText(requireActivity(), "" + error, Toast.LENGTH_SHORT).show()
 }
 }
 AndroidAudioConverter.with(requireActivity())
 .setFile(File(audioLink))
 .setFormat(AudioFormat.AAC)
 .setCallback(callback)
 .convert()
 }

 override fun onFailure(error: java.lang.Exception) {
 toggleLoader(false)
 }
 })
}



After successful conversion from .mp3 to .aac formate, It's extracting audio track and video track for merge


private fun append(): Boolean {

 val progressDialog = ProgressDialog(requireContext())
 Thread {
 requireActivity().runOnUiThread {
 progressDialog.setMessage("Please wait..")
 progressDialog.show()
 }
 val video_list = ArrayList<string>()
 for (i in videopaths.indices) {
 val file: File = File(videopaths.get(i))
 if (file.exists()) {
 val retriever = MediaMetadataRetriever()
 retriever.setDataSource(requireActivity(), Uri.fromFile(file))
 val hasVideo =
 retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO)
 val isVideo = "yes" == hasVideo
 if (isVideo /*&& file.length() > 1000*/) {
 Log.d("resp", videopaths.get(i))
 video_list.add(videopaths.get(i))
 }
 }
 }
 try {
 val inMovies = arrayOfNulls<movie>(video_list.size)
 for (i in video_list.indices) {
 inMovies[i] = MovieCreator.build(video_list[i])
 }
 val videoTracks: MutableList<track> =
 LinkedList()
 val audioTracks: MutableList<track> =
 LinkedList()
 for (m in inMovies) {
 for (t in m!!.tracks) {
 if (t.handler == "soun") {
 audioTracks.add(t)
 }
 if (t.handler == "vide") {
 videoTracks.add(t)
 }
 }
 }
 val result = Movie()
 if (audioTracks.size > 0) {
 result.addTrack(AppendTrack(*audioTracks.toTypedArray()))
 }
 if (videoTracks.size > 0) {
 result.addTrack(AppendTrack(*videoTracks.toTypedArray()))
 }
 val out = DefaultMp4Builder().build(result)
 var outputFilePath: String? = null
 outputFilePath = Variables.outputfile

 /*if (audio != null) {
 Variables.outputfile
 } else {
 Variables.outputfile2
 }*/

 val fos = FileOutputStream(File(outputFilePath))
 out.writeContainer(fos.channel)
 fos.close()

 requireActivity().runOnUiThread {
 progressDialog.dismiss()

 Merge_withAudio()

 /* if (audio != null) else {
 //Go_To_preview_Activity()
 }*/
 }
 } catch (e: java.lang.Exception) {
 }
 }.start()

 return true
}
</track></track></movie></string>


This will add the selected audio with the recorded video


fun Merge_withAudio() {
 val root = Environment.getExternalStorageDirectory().toString()

 // Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.file_copy);
 //String audio_file =Variables.app_folder+Variables.SelectedAudio_AAC;

 //String filename = "android.resource://" + getPackageName() + "/raw/file_copy.aac";
 val audio_file: String = audioLink!!
 Log.e("Merge ", audio_file)
 val video = "$root/output.mp4"

 val bundle=Bundle()
 bundle.putString("FinalVideo", createdVideo?.absolutePath)

 val merge_video_audio = Merge_Video_Audio(this, bundle, object : AsyncResponse {
 override fun processFinish(output: Bundle?) {

 requireActivity().runOnUiThread {
 finalVideo = bundle.getString("FinalVideo")
 createdVideo = File(finalVideo)

 Log.e("Final Path ", finalVideo)

 createThumb {
 setUpExoPlayer()
 }
 }

 }
 })
 merge_video_audio.doInBackground(audio_file, video, createdVideo?.absolutePath)
}


 public class Merge_Video_Audio extends AsyncTask {

 ProgressDialog progressDialog;
 RecentCompletedVideoFragment context;
 public AsyncResponse delegate = null;


Bundle bundleValue;

String audio,video,output;

public Merge_Video_Audio(RecentCompletedVideoFragment context, Bundle bundle , AsyncResponse delegate ){
 this.context=context;
 this.bundleValue=bundle;
 this.delegate=delegate;
 progressDialog=new ProgressDialog(context.requireContext());
 progressDialog.setMessage("Please Wait...");
}

@Override
protected void onPreExecute() {
 super.onPreExecute();
}

@Override
public String doInBackground(String... strings) {
 try {
 progressDialog.show();
 }catch (Exception e){

 }
 audio=strings[0];
 video=strings[1];
 output=strings[2];

 Log.d("resp",audio+"----"+video+"-----"+output);

 Thread thread = new Thread(runnable);
 thread.start();

 return null;
}


@Override
protected void onPostExecute(String s) {
 super.onPostExecute(s);
 Log.e("On Post Execute ", "True");


}


 public void Go_To_preview_Activity(){

 delegate.processFinish(bundleValue);
 }

 public Track CropAudio(String videopath, Track fullAudio){
 try {

 IsoFile isoFile = new IsoFile(videopath);

 double lengthInSeconds = (double)
 isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
 isoFile.getMovieBox().getMovieHeaderBox().getTimescale();


 Track audioTrack = (Track) fullAudio;


 double startTime1 = 0;
 double endTime1 = lengthInSeconds;


 long currentSample = 0;
 double currentTime = 0;
 double lastTime = -1;
 long startSample1 = -1;
 long endSample1 = -1;


 for (int i = 0; i < audioTrack.getSampleDurations().length; i++) {

 long delta = audioTrack.getSampleDurations()[i];

 if (currentTime > lastTime && currentTime <= startTime1) {
 // current sample is still before the new starttime
 startSample1 = currentSample;
 }
 if (currentTime > lastTime && currentTime <= endTime1) {
 // current sample is after the new start time and still before the new endtime
 endSample1 = currentSample;
 }

 lastTime = currentTime;
 currentTime += (double) delta / (double) audioTrack.getTrackMetaData().getTimescale();
 currentSample++;
 }

 CroppedTrack cropperAacTrack = new CroppedTrack(fullAudio, startSample1, endSample1);

 return cropperAacTrack;

 } catch (IOException e) {
 e.printStackTrace();
 }

 return fullAudio;
}



 public Runnable runnable =new Runnable() {
 @Override
 public void run() {

 try {

 Movie m = MovieCreator.build(video);


 List nuTracks = new ArrayList<>();

 for (Track t : m.getTracks()) {
 if (!"soun".equals(t.getHandler())) {

 Log.e("Track ",t.getName());
 nuTracks.add(t);
 }
 }

 Log.e("Path ",audio.toString());


 try {
 // Track nuAudio = new AACTrackImpl();
 Track nuAudio = new AACTrackImpl(new FileDataSourceImpl(audio));

 Track crop_track = CropAudio(video, nuAudio);

 nuTracks.add(crop_track);

 m.setTracks(nuTracks);

 Container mp4file = new DefaultMp4Builder().build(m);

 FileChannel fc = new FileOutputStream(new File(output)).getChannel();
 mp4file.writeContainer(fc);
 fc.close();

 }catch (FileNotFoundException fnfe){
 fnfe.printStackTrace();
 }catch(IOException ioe){
 ioe.printStackTrace();
 }


 try {

 progressDialog.dismiss();
 }catch (Exception e){
 Log.d("resp",e.toString());

 }finally {
 Go_To_preview_Activity();

 }

 } catch (IOException e) {
 e.printStackTrace();
 Log.d("resp",e.toString());

 }

 }

 };

 }



This solution is also not working in all the devices.


Can anyone suggest where i am going wrong or any solution for it ?


-
How to play and seek fragmented MP4 audio using MSE SourceBuffer ?
29 juin 2024, par Stefan FalkNote :




If you end up here, you might want to take a look at shaka-player and the accompanying shaka-streamer. Use it. Don't implement this yourself unless you really have to.




I am trying for quite some time now to be able to play an audio track on Chrome, Firefox, Safari, etc. but I keep hitting brick walls. My problem is currently that I am just not able to seek within a fragmented MP4 (or MP3).


At the moment I am converting audio files such as MP3 to fragmented MP4 (fMP4) and send them chunk-wise to the client. What I do is defining a
CHUNK_DURACTION_SEC
(chunk duration in seconds) and compute a chunk size like this :

chunksTotal = Math.ceil(this.track.duration / CHUNK_DURATION_SEC);
chunkSize = Math.ceil(this.track.fileSize / this.chunksTotal);



With this I partition the audio file and can fetch it entirely jumping
chunkSize
-many bytes for each chunk :

-----------------------------------------
| chunk 1 | chunk 2 | ... | chunk n |
-----------------------------------------



How audio files are converted to fMP4


ffmpeg -i input.mp3 -acodec aac -b:a 256k -f mp4 \
 -movflags faststart+frag_every_frame+empty_moov+default_base_moof \
 output.mp4



This seems to work with Chrome and Firefox (so far).


How chunks are appended


After following this example, and realizing that it's simply not working as it is explained here, I threw it away and started over from scratch. Unfortunately without success. It's still not working.


The following code is supposed to play a track from the very beginning to the very end. However, I also need to be able to seek. So far, this is simply not working. Seeking will just stop the audio after the
seeking
event got triggered.

The code


/* Desired chunk duration in seconds. */
const CHUNK_DURATION_SEC = 20;

const AUDIO_EVENTS = [
 'ended',
 'error',
 'play',
 'playing',
 'seeking',
 'seeked',
 'pause',
 'timeupdate',
 'canplay',
 'loadedmetadata',
 'loadstart',
 'updateend',
];


class ChunksLoader {

 /** The total number of chunks for the track. */
 public readonly chunksTotal: number;

 /** The length of one chunk in bytes */
 public readonly chunkSize: number;

 /** Keeps track of requested chunks. */
 private readonly requested: boolean[];

 /** URL of endpoint for fetching audio chunks. */
 private readonly url: string;

 constructor(
 private track: Track,
 private sourceBuffer: SourceBuffer,
 private logger: NGXLogger,
 ) {

 this.chunksTotal = Math.ceil(this.track.duration / CHUNK_DURATION_SEC);
 this.chunkSize = Math.ceil(this.track.fileSize / this.chunksTotal);

 this.requested = [];
 for (let i = 0; i < this.chunksTotal; i++) {
 this.requested[i] = false;
 }

 this.url = `${environment.apiBaseUrl}/api/tracks/${this.track.id}/play`;
 }

 /**
 * Fetch the first chunk.
 */
 public begin() {
 this.maybeFetchChunk(0);
 }

 /**
 * Handler for the "timeupdate" event. Checks if the next chunk should be fetched.
 *
 * @param currentTime
 * The current time of the track which is currently played.
 */
 public handleOnTimeUpdate(currentTime: number) {

 const nextChunkIndex = Math.floor(currentTime / CHUNK_DURATION_SEC) + 1;
 const hasAllChunks = this.requested.every(val => !!val);

 if (nextChunkIndex === (this.chunksTotal - 1) && hasAllChunks) {
 this.logger.debug('Last chunk. Calling mediaSource.endOfStream();');
 return;
 }

 if (this.requested[nextChunkIndex] === true) {
 return;
 }

 if (currentTime < CHUNK_DURATION_SEC * (nextChunkIndex - 1 + 0.25)) {
 return;
 }

 this.maybeFetchChunk(nextChunkIndex);
 }

 /**
 * Fetches the chunk if it hasn't been requested yet. After the request finished, the returned
 * chunk gets appended to the SourceBuffer-instance.
 *
 * @param chunkIndex
 * The chunk to fetch.
 */
 private maybeFetchChunk(chunkIndex: number) {

 const start = chunkIndex * this.chunkSize;
 const end = start + this.chunkSize - 1;

 if (this.requested[chunkIndex] == true) {
 return;
 }

 this.requested[chunkIndex] = true;

 if ((end - start) == 0) {
 this.logger.warn('Nothing to fetch.');
 return;
 }

 const totalKb = ((end - start) / 1000).toFixed(2);
 this.logger.debug(`Starting to fetch bytes ${start} to ${end} (total ${totalKb} kB). Chunk ${chunkIndex + 1} of ${this.chunksTotal}`);

 const xhr = new XMLHttpRequest();
 xhr.open('get', this.url);
 xhr.setRequestHeader('Authorization', `Bearer ${AuthenticationService.getJwtToken()}`);
 xhr.setRequestHeader('Range', 'bytes=' + start + '-' + end);
 xhr.responseType = 'arraybuffer';
 xhr.onload = () => {
 this.logger.debug(`Range ${start} to ${end} fetched`);
 this.logger.debug(`Requested size: ${end - start + 1}`);
 this.logger.debug(`Fetched size: ${xhr.response.byteLength}`);
 this.logger.debug('Appending chunk to SourceBuffer.');
 this.sourceBuffer.appendBuffer(xhr.response);
 };
 xhr.send();
 };

}

export enum StreamStatus {
 NOT_INITIALIZED,
 INITIALIZING,
 PLAYING,
 SEEKING,
 PAUSED,
 STOPPED,
 ERROR
}

export class PlayerState {
 status: StreamStatus = StreamStatus.NOT_INITIALIZED;
}


/**
 *
 */
@Injectable({
 providedIn: 'root'
})
export class MediaSourcePlayerService {

 public track: Track;

 private mediaSource: MediaSource;

 private sourceBuffer: SourceBuffer;

 private audioObj: HTMLAudioElement;

 private chunksLoader: ChunksLoader;

 private state: PlayerState = new PlayerState();

 private state$ = new BehaviorSubject<playerstate>(this.state);

 public stateChange = this.state$.asObservable();

 private currentTime$ = new BehaviorSubject<number>(null);

 public currentTimeChange = this.currentTime$.asObservable();

 constructor(
 private httpClient: HttpClient,
 private logger: NGXLogger
 ) {
 }

 get canPlay() {
 const state = this.state$.getValue();
 const status = state.status;
 return status == StreamStatus.PAUSED;
 }

 get canPause() {
 const state = this.state$.getValue();
 const status = state.status;
 return status == StreamStatus.PLAYING || status == StreamStatus.SEEKING;
 }

 public playTrack(track: Track) {
 this.logger.debug('playTrack');
 this.track = track;
 this.startPlayingFrom(0);
 }

 public play() {
 this.logger.debug('play()');
 this.audioObj.play().then();
 }

 public pause() {
 this.logger.debug('pause()');
 this.audioObj.pause();
 }

 public stop() {
 this.logger.debug('stop()');
 this.audioObj.pause();
 }

 public seek(seconds: number) {
 this.logger.debug('seek()');
 this.audioObj.currentTime = seconds;
 }

 private startPlayingFrom(seconds: number) {
 this.logger.info(`Start playing from ${seconds.toFixed(2)} seconds`);
 this.mediaSource = new MediaSource();
 this.mediaSource.addEventListener('sourceopen', this.onSourceOpen);

 this.audioObj = document.createElement('audio');
 this.addEvents(this.audioObj, AUDIO_EVENTS, this.handleEvent);
 this.audioObj.src = URL.createObjectURL(this.mediaSource);

 this.audioObj.play().then();
 }

 private onSourceOpen = () => {

 this.logger.debug('onSourceOpen');

 this.mediaSource.removeEventListener('sourceopen', this.onSourceOpen);
 this.mediaSource.duration = this.track.duration;

 this.sourceBuffer = this.mediaSource.addSourceBuffer('audio/mp4; codecs="mp4a.40.2"');
 // this.sourceBuffer = this.mediaSource.addSourceBuffer('audio/mpeg');

 this.chunksLoader = new ChunksLoader(
 this.track,
 this.sourceBuffer,
 this.logger
 );

 this.chunksLoader.begin();
 };

 private handleEvent = (e) => {

 const currentTime = this.audioObj.currentTime.toFixed(2);
 const totalDuration = this.track.duration.toFixed(2);
 this.logger.warn(`MediaSource event: ${e.type} (${currentTime} of ${totalDuration} sec)`);

 this.currentTime$.next(this.audioObj.currentTime);

 const currentStatus = this.state$.getValue();

 switch (e.type) {
 case 'playing':
 currentStatus.status = StreamStatus.PLAYING;
 this.state$.next(currentStatus);
 break;
 case 'pause':
 currentStatus.status = StreamStatus.PAUSED;
 this.state$.next(currentStatus);
 break;
 case 'timeupdate':
 this.chunksLoader.handleOnTimeUpdate(this.audioObj.currentTime);
 break;
 case 'seeking':
 currentStatus.status = StreamStatus.SEEKING;
 this.state$.next(currentStatus);
 if (this.mediaSource.readyState == 'open') {
 this.sourceBuffer.abort();
 }
 this.chunksLoader.handleOnTimeUpdate(this.audioObj.currentTime);
 break;
 }
 };

 private addEvents(obj, events, handler) {
 events.forEach(event => obj.addEventListener(event, handler));
 }

}
</number></playerstate>


Running it will give me the following output :






Apologies for the screenshot but it's not possible to just copy the output without all the stack traces in Chrome.




What I also tried was following this example and call
sourceBuffer.abort()
but that didn't work. It looks more like a hack that used to work years ago but it's still referenced in the docs (see "Example" -> "You can see something similar in action in Nick Desaulnier's bufferWhenNeeded demo ..").

case 'seeking':
 currentStatus.status = StreamStatus.SEEKING;
 this.state$.next(currentStatus); 
 if (this.mediaSource.readyState === 'open') {
 this.sourceBuffer.abort();
 } 
 break;



Trying with MP3


I have tested the above code under Chrome by converting tracks to MP3 :


ffmpeg -i input.mp3 -acodec aac -b:a 256k -f mp3 output.mp3



and creating a
SourceBuffer
usingaudio/mpeg
as type :

this.mediaSource.addSourceBuffer('audio/mpeg')



I have the same problem when seeking.


The issue wihout seeking


The above code has another issue :


After two minutes of playing, the audio playback starts to stutter and comes to a halt prematurely. So, the audio plays up to a point and then it stops without any obvious reason.


For whatever reason there is another
canplay
andplaying
event. A few seconds after, the audio simply stops..