Connaitre la durée d'un ficher MP3

  Information

Vous voulez afficher la durée de vos MP3 sur votre site, ou mettre un aperçu du MP3 sur votre site, genre les 30 premieres secondes à partir de la 10 ieme seconde, alors ce code est fait pour vous!

Ce code a 3 fonctions :

  • Supprime les tags ID3 d'un fichier MP3 si ils existent
  • Donne la durée totale du fichier MP3
  • Coupe un fichier MP3 pour en extraire les n secondes à partir de la n seconde:

Ce code est inspiré de la classe falahati sur le GitHub.

Des exemples sont fournis à la fin du code.

Ce code source est utilisé sur le site web : Place de la Musique  

  code source classé dans  Classes

 
 01    
 02    
 03    
 04    
 05    
 06    
 07    
 08    
 09    
 10    
 11    
 12    
 13    
 14    
 15    
 16    
 17    
 18    
 19    
 20    
 21    
 22    
 23    
 24    
 25    
 26    
 27    
 28    
 29    
 30    
 31    
 32    
 33    
 34    
 35    
 36    
 37    
 38    
 39    
 40    
 41    
 42    
 43    
 44    
 45    
 46    
 47    
 48    
 49    
 50    
 51    
 52    
 53    
 54    
 55    
 56    
 57    
 58    
 59    
 60    
 61    
 62    
 63    
 64    
 65    
 66    
 67    
 68    
 69    
 70    
 71    
 72    
 73    
 74    
 75    
 76    
 77    
 78    
 79    
 80    
 81    
 82    
 83    
 84    
 85    
 86    
 87    
 88    
 89    
 90    
 91    
 92    
 93    
 94    
 95    
 96    
 97    
 98    
 99    
 100    
 101    
 102    
 103    
 104    
 105    
 106    
 107    
 108    
 109    
 110    
 111    
 112    
 113    
 114    
 115    
 116    
 117    
 118    
 119    
 120    
 121    
 122    
 123    
 124    
 125    
 126    
 127    
 128    
 129    
 130    
 131    
 132    
 133    
 134    
 135    
 136    
 137    
 138    
 139    
 140    
 141    
 142    
 143    
 144    
 145    
 146    
 147    
 148    
 149    
 150    
 151    
 152    
 153    
 154    
 155    
 156    
 157    
 158    
 159    
 160    
 161    
 162    
 163    
 164    
 165    
 166    
 167    
 168    
 169    
 170    
 171    
 172    
 173    
 174    
 175    
 176    
 177    
 178    
 179    
 180    
 181    
 182    
 183    
 184    
 185    
 186    
 187    
 188    
 189    
 190    
 191    
 192    
 193    
 194    
 195    
 196    
 197    
 198    
 199    
 200    
 201    
 202    
 203    
 204    
 205    
 206    
 207    
 208    
 209    
 210    
 211    
 212    
 213    
 214    
 215    
 216    
 217    
 218    
 219    
 220    
 221    
 222    
 223    
 224    
 225    
 226    
 227    
 228    
 229    
 230    
 231    
 232    
 233    
 234    
 235    
 236    
 237    
 238    
 239    
 240    
 241    
 242    
 243    
 244    
 245    
 246    
 247    
 248    
 249    
 250    
 251    
 252    
 253    
 254    
 255    
 256    
 257    
 258    
 259    
 260    
 261    
 262    
 263    
 264    
 265    
 266    
 267    
 268    
 269    
 270    
 271    
 272    
 273    
 274    
 275    
 276    
 277    
 278    
 279    
 280    
 281    
 282    
 283    
 284    
 285    
 286    
 287    
 288    
 289    
 290    
 291    
 292    
 293    
 294    
 295    
 296    
 297    
 298    
 299    
 300    
 301    
 302    
 303    
 304    
 305    
 306    
 307    
 308    
 309    
 310    
 311    
 312    
 313    
 314    
 315    
 316    
 317    
 318    
 319    
 320    
 321    
 322    
 323    
 324    
 325    
 326    
 327    
 328    
 329    
 330    
 331    
 332    
 333    
 334    
 335    
 336    
 337    
 338    
 339    
 340    
 341    
 342    
 343    
 344    
 345    
 346    
 347    
 348    
 349    
 350    
 351    
 352    
 353    
 354    
 355    
 356    
 357    
 358    
 359    
 360    
 361    
 362    
 363    
 364    
 365    
 366    
 367    
 368    
 369    
 370    
 371    
 372    
 373    
 374    
 375    
 376    
 377    
 378    
 379    
 380    
 381    
 382    
 383    
 384    
 385    
 386    
 387    
 388    
 389    
 390    
 391    
 392    
 393    
 394    
 395    
 396    
 397    
 398    
 399    
 400    
 401    
 402    
 403    
 404    
 405    
 406    
 407    
 408    
 409    
 410    
 411    
 412    
 413    
 414    
 415    
 416    
 417    
 418    
 419    
 420    
 421    
 422    
 423    
 424    
 425    
 426    
 427    
 428    
 429    
 430    
 431    
 432    
 433    
 434    
 435    
 436    
 437    
 438    
 439    
 440    
 441    
 442    
 443    
 444    
 445    
 446    
 447    
 448    
 449    
 450    
 451    
 452    
 453    
 454    
 455    
 456    
 457    
 458    
 459    
 460    
 461    
 462    
 463    
 464    
 465    
 466    
 467    
 468    
 469    
 470    
 471    
 472    
 473    
 474    
 475    
 476    
 477    
 478    
 479    
 480    
 481    
 482    
 483    
 484    
 485    
 486    
 487    
 488    
 489    
 490    
 491    
 492    
 493    
 494    
 495    
 496    
 497    
 498    
 499    
 500    
 501    
 502    
 503    
 504    
 505    
 506    
 507    
 508    
 509    
 510    
 511    
 512    
 513    
 514    
 515    
 516    
 517    
 518    
 519    
 520    
 521    
 522    
 523    
 524    
 525    
 526    
 527    
 528    
 529    
 530    
 531    
 532    
 533    
 534    
 535    
 536    
 537    
 538    
 539    
 540    
 541    
 542    
 543    
 544    
 545    
 546    
 547    
 548    
 549    
 550    
 551    
 552    
 553    
 554    
 555    
 556    
 557    
 558    
 559    
 560    
 561    
 562    
 563    
 564    
 565    
 566    
 567    
 568    
 569    
 570    
 571    
 572    
 573    
 574    
 575    
 576    
 577    
 578    
 579    
 580    
 581    
 582    
 583    
 584    
 585    
 586    
 587    
 588    
 589    
 590    
 591    
 592    
 593    
 594    
 595    
 596    
 597    
 598    
 599    
 600    
 601    
 602    
 603    
 604    
 605    
 606    
 607    
 608    
 609    
 610    
 611    
 612    
 613    
 614    
 615    
 616    
 617    
 618    
 619    
 620    
 621    
 622    
 623    
 624    
 625    
 626    
 627    
 628    
 629    
 630    
 631    
 632    
 633    
 634    
 635    
 636    
 637    
 638    
 639    
 640    
 641    
 642    
 643    
 644    
 645    
 646    
 647    
 648    
 649    
 650    
 651    
 652    
 653    
 654    
 655    
 656    
 657    
 658    
 659    
 660    
 661    
 662    
 663    
 664    
 665    
 666    
 667    
 668    
 669    
 670    
 671    
 672    
 673    
 674    
 675    
 676    
 677    
 678    
 679    
 680    
 681    
 682    
 683    
 684    
 685    
 686    
 687    
 688    
 689    
 690    
 691    
 692    
 693    
 694    
 695    
 696    
 697    
 698    
 699    
 700    
 701    
 702    
 703    
 704    
 705    
 706    
 707    
 708    
 709    
 710    
 711    
 712    
 713    
 714    
 715    
 716    
 717    
 718    
 719    
 720    
 721    
 722    
 723    
 724    
 725    
 726    
 727    
 728    
 729    
 730    
 731    
 732    
 733    
 734    
 735    
 736    
 737    
 738    
 739    
 740    
 741    
 742    
 743    
 744    
 745    
 746    
 747    
 748    
 749    
 750    
 751    
 752    
 753    
 754    
 755    
 756    
 757    
 758    
 759    
 760    
 761    
 762    
 763    
 764    
 765    
 766    
 767    
 768    
 769    
 770    
 771    
 772    
 773    
 774    
 775    
 776    
 777    
 778    
 779    
 780    
 781    
 782    
 783    
 784    
 785    
 786    
 787    
 788    
 789    
 790    
 791    
 792    
 793    
 794    
 795    
 796    
 797    
 798    
 799    
 800    
 801    
 802    
 803    
 804    
 805    
 806    
 807    
 808    
 809    
 810    
 811    
 812    
 813    
 814    
 815    
 816    
 817    
 818    
 819    
 820    
 821    
 822    
 823    
 824    
 825    
 826    
 827    
 828    
 829    
 830    
 831    
 832    
 833    
 834    
 835    
 836    
 837    
 838    
 839    
 840    
 841    
 842    
 843    
 844    
 845    
 846    
 847    
 848    
 849    
 850    
 851    
 852    
 853    
 854    
 855    
 856    
 857    
 858    
 859    
 860    
 861    
 862    
 863    
 864    
 865    
 866    
 867    
 868    
 869    
 870    
 871    
 872    
 873    
 874    
 875    
 876    
 877    
 878    
 879    
 880    
 881    
 882    
 883    
 884    
 885    
 886    
 887    
 888    
 889    
 890    
 891    
 892    
 893    
 894    
 895    
 896    
 897    
 898    
 899    
 900    
 901    
 902    
 903    
 904    
 905    
 906    
 907    
 908    
 909    
 910    
 911    
 912    
 913    
 914    
 915    
 916    
 917    
 918    
 919    
 920    
 921    
 922    
 923    
 924    
 925    
 926    
 927    
 928    
 929    
 930    
 931    
 932    
 933    
 934    
 935    
 936    
 937    
 938    
 939    
 940    
 941    
 942    
 943    
 944    
 945    
 946    
 947    
 948    
 949    
 950    
 951    
 952    
 953    
 954    
 955    
 956    
 957    
 958    
 959    
 960    
 961    
 962    
 963    
 964    
 965    
 966    
 967    
 968    
 969    
 970    
 971    
 972    
 973    
 974    
 975    
 976    
 977    
 978    
 979    
 980    
 981    
 982    
 983    
 984    
 985    
 986    
 987    
 988    
 989    
 990    
 991    
 992    
 993    
 994    
 995    
 996    
 997    
 998    
 999    
 1000    
 1001    
 1002    
 1003    
 1004    
 1005    
 1006    
 1007    
 1008    
 1009    
 1010    
 1011    
 1012    
 1013    
 1014    
 1015    
 1016    
 1017    
 1018    
 1019    
 1020    
 1021    
 1022    
 1023    
 1024    
 1025    
 1026    
 1027    
 1028    
 1029    
 1030    
 1031    
 1032    
 1033    
 1034    
 1035    
 1036    
 1037    
 1038    
 1039    
 1040    
 1041    
 1042    
 1043    
 1044    
 1045    
 1046    
 1047    
 1048    
 1049    
 1050    
 1051    
 1052    
 1053    
 1054    
 1055    
 1056    
 1057    
 1058    
 1059    
 1060    
 1061    
 1062    
 1063    
 1064    
 1065    
 1066    
 1067    
 1068    
 1069    
 1070    
 1071    
 1072    
 1073    
 1074    
 1075    
 1076    
 1077    
 1078    
 1079    
 1080    
 1081    
 1082    
 1083    
 1084    
 1085    
 1086    
 1087    
 1088    
 1089    
 1090    
 1091    
 1092    
 1093    
 1094    
 1095    
 1096    
 1097    
 1098    
 1099    
 1100    
                               
<?php
/*---------------------------------------------------------------*/
/*
    Titre : Connaitre la durée d'un ficher MP3                                                                           
                                                                                                                          
    URL   : https://phpsources.net/code_s.php?id=1129
    Auteur           : Place de la Musique                                                                                
    Website auteur   : https://www.placedelamusique.net/                                                                  
    Date édition     : 20 Jan 2020                                                                                        
    Date mise à jour : 20 Jan 2020                                                                                       
    Rapport de la maj:                                                                                                    
    - fonctionnement du code vérifié                                                                                    
*/
/*---------------------------------------------------------------*/

    class MpegAudioFrameHeader
      {
        /**
         * MPEG Audio Version 1
         */
        const Version_10  1;

        /**
         * MPEG Audio Version 2
         */
        const Version_20  2;

        /**
         * MPEG Audio Version 2.5
         */
        const Version_25  2.5;

        /**
         * MPEG Audio Profile 1
         */
        const Profile_1    1;

        /**
         * MPEG Audio Profile 2
         */
        const Profile_2    2;

        /**
         * MPEG Audio Profile 3
         */
        const Profile_3    3;

        /**
         * MPEG Audio Stereo Mode
         */
        const Mode_Stereo 0;

        /**
         * MPEG Audio Joint Stereo Mode
         */
        const Mode_JointStereo 1;

        /**
         * MPEG Audio Dual Channel Mono Mode
         */
        const Mode_DualChannel 2;

        /**
         * MPEG Audio Single Channel Mono Mode
         */
        const Mode_SingleChannel 3;

        /**
         * MPEG Audio Profile 3 Intensity Stereo Disabled
         */
        const IntensityStereo_Disable 0;

        /**
         * MPEG Audio Profile 3 Intensity Stereo Auto Frequency Selection
         */
        const IntensityStereo_Auto 1;

        /**

         * MPEG Audio Profile 1 & Profile 2 Intensity Stereo Frequency Bands 4 to 31
         */
        const IntensityStereo_Bands4_31 2;

        /**

         * MPEG Audio Profile 1 & Profile 2 Intensity Stereo Frequency Bands 8 to 31
         */
        const IntensityStereo_Bands8_31 3;

        /**

         * MPEG Audio Profile 1 & Profile 2 Intensity Stereo Frequency Bands 12 to 31
         */
        const IntensityStereo_Bands12_31 4;

        /**

         * MPEG Audio Profile 1 & Profile 2 Intensity Stereo Frequency Bands 16 to 31
         */
        const IntensityStereo_Bands16_31 5;

        /**
         * Holds the bit rate of the frame
         * @var int
         */
        private $bitRate 0;

        /**
         * Holds the sample rate of the frame
         * @var int
         */
        private $sampleRate 0;

        /**
         * Holds the MPEG audio version of the frame
         * @var int
         */
        private $version = -1;

        /**
         * Holds the MPEG audio profile of the frame
         * @var int
         */
        private $profile = -1;

        /**
         * Holds the estimated duration of this frame
         * @var double
         */
        private $duration 0.0;

        /**
         * Holds the frame's data offset in MPEG audio
         * @var int
         */
        private $offset 0;

        /**
         * Holds the frame's data length in MPEG audio
         * @var int
         */
        private $length 0;

        /**
         * Holds the frame's ending padding in bytes
         * @var int
         */
        private $padding 0;

        /**
         * Holds the frame's error protection status
         * @var bool
         */
        private $errorProtection false;

        /**
         * Holds the frame's extra information status
         * @var bool
         */
        private $privateBit false;

        /**
         * Holds the frame's copyrighted work bit status
         * @var bool
         */
        private $copyrighted false;

        /**
         * Holds the frame's copyrighted work originality bit status
         * @var bool
         */
        private $original false;

        /**
         * Holds the frame's channels mode
         * @var int
         */
        private $mode self::Mode_Stereo;

        /**
         * Holds the frame's middle-side stereo joining availability status
         * @var bool
         */
        private $middleSideStereoJoining false;

        /**
         * Holds the frame's intensity stereo operation mode
         * @var int
         */
        private $intensityStereoMode self::IntensityStereo_Disable;

        /**

         * Holds the list of every byte along with their equivalent binary representation
         * @var array
         */
        private static $binaryTable = [];

        /**
         * Holds the list of standard bit rates for MPEG audio
         * @var array
         */
        private static $bitRateTable = [];

        /**
         * Holds the list of standard sample rates for MPEG audio
         * @var array
         */
        private static $sampleRateTable = [];

        /**
         * Gets the frame's bit rate in bps
         * @return int
         */
        public function getBitRate() {
          return $this->bitRate;
        }

        /**
         * Gets the frame's sample rate in Hz
         * @return int
         */
        public function getSampleRate() {
          return $this->sampleRate;
        }

        /**
         * Gets the frame's MPEG audio version number
         * @return int
         */
        public function getVersion() {
          return $this->version;
        }

        /**
         * Gets the frame's MPEG audio layer profile number
         * @return int
         */
        public function getLayerProfile() {
          return $this->profile;
        }

        /**
         * Gets the frame's estimated duration
         * @return int
         */
        public function getDuration() {
          return $this->duration;
        }

        /**
         * Gets the frame's data offset in MPEG audio
         * @return int
         */
        public function getOffset() {
          return $this->offset;
        }

        /**
         * Gets the frame's data length in MPEG audio
         * @return int
         */
        public function getLength() {
          return $this->length;
        }

        /**
         * Gets the frame's ending padding in bytes
         * @return int
         */
        public function getPadding() {
          return $this->padding;
        }

        /**
         * Gets the frame's error protection status
         * @return bool
         */
        public function isErrorProtectionEnable() {
          return $this->errorProtection;
        }

        /**
         * Gets the frame's private bit information status
         * @return bool
         */
        public function isPrivateBitActive() {
          return $this->privateBit;
        }

        /**
         * Gets the frame's copyrighted work bit status
         * @return bool
         */
        public function isCopyrighted() {
          return $this->copyrighted;
        }

        /**
         * Gets the frame's copyrighted work originality bit status
         * @return bool
         */
        public function isOriginal() {
          return $this->original;
        }

        /**
         * Gets the frame's channels mode
         * @return int
         */
        public function getChannelMode() {
          return $this->mode;
        }

        /**
         * Gets the frame's middle side stereo joining availability status
         * @return bool
         */
        public function isMiddleSideStereoJoiningEnable() {
          return $this->middleSideStereoJoining;
        }

        /**
         * Gets the frame's intensity stereo mode
         * @return int
         */
        public function getIntensityStereoMode() {
          return $this->intensityStereoMode;
        }

        /**

         * Creates a new instance of this class, also fills the binary table for later use
         */
        private function __construct() {
          if (!self::$binaryTable) {
            for ($i 0$i 256$i ++) {
              self::$binaryTable[chr($i)] = sprintf('%08b'$i);
            }
          }
          if (!self::$bitRateTable) {
            self::$bitRateTable array(
              '0000' => array(00000),
              '0001' => array(323232328),
              '0010' => array(6448404816),
              '0011' => array(9656485624),
              '0100' => array(12864566432),
              '0101' => array(16080648040),
              '0110' => array(19296809648),
              '0111' => array(2241129611256),
              '1000' => array(25612811212864),
              '1001' => array(28816012814480),
              '1010' => array(32019216016096),
              '1011' => array(352224192176112),
              '1100' => array(384256224192128),
              '1101' => array(416320256224144),
              '1110' => array(448384320256160),
              '1111' => array(-1, -1, -1, -1, -1)
            );
          }
          if (!self::$sampleRateTable) {
            self::$sampleRateTable array(
              self::Version_10 => array(
                '00' => 44100,
                '01' => 48000,
                '10' => 32000,
                '11' => 0
              ),
              self::Version_20 => array(
                '00' => 22050,
                '01' => 24000,
                '10' => 16000,
                '11' => 0
              ),
              self::Version_25 => array(
                '00' => 11025,
                '01' => 12000,
                '10' => 8000,
                '11' => 0
              )
            );
          }
        }

        /**

         * Tries to parse and return a new MpegAudioFrameHeader object from the provided data, false on failure
         * @param string $headerBytes
         * @param int $offset
         * @return bool|\falahati\PHPMP3\MpegAudioFrameHeader
         */
        public static function tryParse($headerBytes$offset) {
          $frame = new self();
          $frame->offset $offset;

          // -------------------------------------------------------------------
          // Converting bytes to their formatted binary string
          $headerBits = [];
          for ($i 0$i strlen($headerBytes); $i ++) {
            $headerBits[] = self::$binaryTable[$headerBytes[$i]];
          }

          // -------------------------------------------------------------------
          // Check header marker
          if (count($headerBits) < || $headerBits[0] !== '11111111' || substr(
$headerBits[1], 03) !== '111') {
            return false;
          }

          // -------------------------------------------------------------------
          // Get version
          switch (substr($headerBits[1], 32)) {
            case '01':
              // Reserved
              return false;
            case '00':
              $frame->version self::Version_25;
              break;
            case '10':
              $frame->version self::Version_20;
              break;
            case '11':
              $frame->version self::Version_10;
              break;
          }

          // -------------------------------------------------------------------
          // Get profile
          switch (substr($headerBits[1], 52)) {
            case '01':
              $frame->profile self::Profile_3;
              break;
            case '00':
              // Reserved
              return false;
            case '10':
              $frame->profile self::Profile_2;
              break;
            case '11':
              $frame->profile self::Profile_1;
              break;
          }

          // -------------------------------------------------------------------
          // Get error protection bit
          $frame->errorProtection = !!(substr($headerBits[1], 71));

          // -------------------------------------------------------------------
          // Get bitrate
          $frame->bitRate = -1;
          $bitRateIndex  substr($headerBits[2], 04);
          if ($frame->version == self::Version_10) {
            switch ($frame->profile) {
              case self::Profile_1:
                $frame->bitRate self::$bitRateTable[$bitRateIndex][0];
                break;
              case self::Profile_2:
                $frame->bitRate self::$bitRateTable[$bitRateIndex][1];
                break;
              case self::Profile_3:
                $frame->bitRate self::$bitRateTable[$bitRateIndex][2];
                break;
            }
          } else {
            switch ($frame->profile) {
              case self::Profile_1:
                $frame->bitRate self::$bitRateTable[$bitRateIndex][3];
                break;
              case self::Profile_2:
              case self::Profile_3:
                $frame->bitRate self::$bitRateTable[$bitRateIndex][4];
                break;
            }
          }
          if ($frame->bitRate <= 0) {
            // Invalid value or bitrate needs calculation
            return false;
          }
          // Convert kbps to bps
          $frame->bitRate *= 1000;

          // -------------------------------------------------------------------
          // Get sample rate
          $frame->sampleRate self::$sampleRateTable[$frame->version][substr(
$headerBits[2], 42)];
          if ($frame->sampleRate <= 0) {
            // Invalid sample rate value
            return false;
          }

          // -------------------------------------------------------------------
          // Get frame padding
          $frame->padding substr($headerBits[2], 61) ? 0;

          // -------------------------------------------------------------------
          // Get protection bit
          $frame->privateBit = !!(substr($headerBits[2], 71));


          // -------------------------------------------------------------------
          // Get audio mode
          switch (substr($headerBits[3], 02)) {
            case '00':
              $frame->mode self::Mode_Stereo;
              break;
            case '01':
              $frame->mode self::Mode_JointStereo;
              break;
            case '10':
              $frame->mode self::Mode_DualChannel;
              break;
            case '11':
              $frame->mode self::Mode_SingleChannel;
              break;
          }
          if ($frame->profile == self::Profile_1 || $frame->profile == self::
Profile_2) {
            $frame->middleSideStereoJoining false;
            switch (substr($headerBits[3], 22)) {
              case '00':
                $frame->intensityStereoMode self::IntensityStereo_Bands4_31;
                break;
              case '01':
                $frame->intensityStereoMode self::IntensityStereo_Bands8_31;
                break;
              case '10':
                $frame->intensityStereoMode self::IntensityStereo_Bands12_31;
                break;
              case '11':
                $frame->intensityStereoMode self::IntensityStereo_Bands16_31;
                break;
            }
          } else if ($frame->profile == self::Profile_3) {
            $frame->intensityStereoMode substr($headerBits[3], 21) ? self::
IntensityStereo_Auto self::IntensityStereo_Disable;
            $frame->middleSideStereoJoining = !!(substr($headerBits[3], 31));
          }

          // -------------------------------------------------------------------
          // Get copyright information
          $frame->copyrighted = !!(substr($headerBits[3], 44));
          $frame->original = !!(substr($headerBits[3], 51));

          // -------------------------------------------------------------------
          // Calculate frame length
          if ($frame->profile == self::Profile_1) {
            $frame->length = (((12 $frame->bitRate) / $frame->sampleRate) + 
$frame->padding) * 4;
          } else if ($frame->profile == self::Profile_2 || $frame->profile == 
self::Profile_3) {
            $frame->length = ((144 $frame->bitRate) / $frame->sampleRate) + 
$frame->padding;
          }
          $frame->length floor($frame->length);
          if ($frame->length <= 0) {
            // Invalid frame length
            return false;
          }

          // -------------------------------------------------------------------
          // Calculate frame duration
          $frame->duration $frame->length $frame->bitRate;

          // -------------------------------------------------------------------
          // Return result
          return $frame;
        }
      }

      /**
       * This class represents and is able to read and manipulate a MPEG audio
       * @author    Soroush Falahati https://falahati.net
       * @copyright  Soroush Falahati (C) 2017
       * @license    LGPL v3 https://www.gnu.org/licenses/lgpl-3.0.en.html
       * @link    https://github.com/falahati/PHP-MP3
       */
      class MpegAudio
      {
        /**
         * Holds MPEG data in memory
         * @var string
         */
        private $memory "";

        /**
         * Holds an integer value pointing in a specific location in the memory
         * @var int
         */
        private $memoryPointer 0;

        /**
         * Holds the length of the memory
         * @var int
         */
        private $memoryLength 0;

        /**
         * Holds MPEG resource stream
         * @var resource
         */
        private $resource null;

        /**

         * Holds an integer number representing the total number of MPEG audio frames
         * @var int
         */
        private $frames = -1;

        /**

         * Holds a float number representing the total duration of the MPEG audio data
         * @var double
         */
        private $duration 0.0;

        /**
         * Holds an array of frame's starting offsets
         * @var int[]|array
         */
        private $frameOffsetTable = [];

        /**
         * Holds an array of frame's starting time
         * @var double[]|array
         */
        private $frameTimingTable = [];

        /**

         * Loads a MP3 file and returns a newly created MpegAudio object, or false on failure
         * @param string $path
         * @return bool|\falahati\PHPMP3\MpegAudio
         */
        public static function fromFile($path) {
          $inMemory true;
          if ($inMemory) {
            return self::fromData(file_get_contents($path));
          } else {
            //return self::fromResource(fopen($path, "cb"));
          }
        }

        /**

         * Creates and returns a MpegAudio object and loads binary data, or false on failure
         * @param string $data
         * @return bool|\falahati\PHPMP3\MpegAudio
         */
        public static function fromData($data) {
          if (!is_string($data)) {
            return false;
          }
          $audio = new MpegAudio();
          $audio->memory $data;
          $audio->memoryLength strlen($audio->memory);
          return $audio;
        }

        //public static function fromResource($resource) {
        //    if (!is_resource($resource)) {
        //        return false;
        //    }
        //    $audio = new MpegAudio();
        //    $audio->resource = $resource;
        //    return $audio;
        //}

        /**
         * Reads a series of bytes from memory or resource
         * @param int $length
         * @param int $index
         * @return string
         */
        private function read($length 0$index = -1) {
          if ($this->resource === null) {
            if ($index 0) {
              $index $this->memoryPointer;
            }
            if ($length == 0) {
              $length $this->memoryLength $index;
            }
            $this->memoryPointer min($this->memoryLength$index $length);
            return substr($this->memory$index$length);
          } else {
            // TODO STREAM
          }
        }

        /**

         * Writes a series of bytes to the memory or resource, replacing older content or appending to the end
         * @param string $data
         * @param int $index
         * @return int
         */
        private function write($data$index = -1) {
          if ($this->resource === null) {
            $length strlen($data);
            $this->slice($length$index);
            return $this->insert($data$index);
          } else {
            // TODO STREAM
          }
        }

        /**
         * Inserts a series of bytes to the memory or resource, increasing size
         * @param string $data
         * @param int $index
         * @return int
         */
        private function insert($data$index = -1) {
          if ($this->resource === null) {
            if ($index 0) {
              $index $this->memoryPointer;
            }
            $length strlen($data);
            $this->memoryPointer $index $length;
            $this->memory substr($this->memory0$index) . $data substr(
$this->memory$index);
            $this->memoryLength += strlen($data);
            return $length;
          } else {
            // TODO STREAM
          }
        }

        /**
         * Removing parts of the memory or resource, decreasing size
         * @param int $length
         * @param int $index
         * @return int
         */
        private function slice($length 0$index = -1) {
          if ($this->resource === null) {
            if ($index 0) {
              $index $this->memoryPointer;
            }
                    if ($length == 0) {
                        $length $this->memoryLength $index;
                    }
            $this->memoryPointer $index;
            $length max(min($this->memoryLength $index$length), 0);
            $this->memory substr($this->memory0$index) . substr($this->
memory$index $length);
            $this->memoryLength -= $length;
            return $length;
          } else {
            // TODO STREAM
          }
        }

        /**

         * Seeking pointer to a specific location, or returns the current pointer location
         * @param int $index
         * @return int|bool
         */
        private function seek($index = -1) {
          if ($index 0) {
            if ($this->resource === null) {
              return $this->memoryPointer;
            } else {
              // TODO STREAM
            }
          }
          if ($this->resource === null) {
            $this->memoryPointer $index;
            return true;
          } else {
            // TODO STREAM
          }
        }

        /**
         * Creates an empty MPEG audio class
         */
        public function __construct() {
          $this->reset();
          $this->memory "";
        }

        /**
         * Resets all extracted data and marks them for recalculation
         */
        private function reset() {
          $this->frames = -1;
          $this->frameTimingTable = [];
          $this->frameOffsetTable = [];
          $this->duration 0.0;
        }

        /**
         * Calculate and extract MPEG audio information
         */
        private function analyze() {
          $offset $this->getStart();
          $this->frames 0;
          $this->frameOffsetTable = [];
          $this->frameTimingTable = [];
          $this->duration 0.0;
          if ($offset !== false) {
            while(true) {
              $frameHeader $this->readFrameHeader($offset);
              if ($frameHeader === false) {
                // Try recovery
                $offset $this->getStart($offset);
                if ($offset !== false) {
                  continue;
                }
                break;
              }
              $this->duration += $frameHeader->getDuration();
              $this->frameOffsetTable[$this->frames] = $frameHeader->getOffset()
;
              $this->frameTimingTable[$this->frames] = $this->duration;
              $this->frames++;
              $offset $frameHeader->getOffset() + $frameHeader->getLength();
              unset($frameHeader);
            }
          }
        }

        /**

         * Calculates the starting offset of the first frame after the specified offset
         * @param int $offset
         * @return bool|int
         */
        private function getStart($offset 0) {
          $offset--;
          while (true) {
            $offset++;
            $byte $this->read(1$offset);
            if ($byte === false) {
              return false;
            }
            if ($byte != chr(255)) {
              continue;
            }
            $frameHeader $this->readFrameHeader($offset);
            if ($frameHeader === false) {
              continue;
            }
            $frameHeader $this->readFrameHeader($frameHeader->getOffset() + 
$frameHeader->getLength());
            if ($frameHeader === false) {
              continue;
            }
            return $offset;
          }
        }

        /**
         * Reads a frame's header and returns a MpegAudioFrameHeader object
         * @param int $offset
         * @return bool|\falahati\PHPMP3\MpegAudioFrameHeader
         */
        private function readFrameHeader($offset) {
          $bytes $this->read(4$offset);
          return MpegAudioFrameHeader::tryParse($bytes$offset);
        }

        /**
         * Saves this MPEG audio to a file, returns this object
         * @param string $path
         * @return \falahati\PHPMP3\MpegAudio
         */
        public function saveFile($path) {
          if ($this->resource === null) {
            file_put_contents($path$this->memory);
            return $this;
          } else {
            fflush($this->resource);
            // TODO COPY STREAM
            return $this;
          }
        }

        /**

         * Closes all resources and frees the memory, returns MPEG audio as binary string, or a boolean value indicating the operation success
         * @return bool|string
         */
        public function close() {
          if ($this->resource === null) {
            $data $this->memory;
            $this->memory "";
            $this->memoryLength 0;
            $this->memoryPointer 0;
            return $data;
          }
          if ($this->resource !== null && fclose($this->resource)) {
            $this->resource null;
            return true;
          }
          return false;
        }

        /**
         * Gets the number of frames in this MPEG audio
         * @return int
         */
        public function getFrameCounts() {
          if ($this->frames 0) {
            $this->analyze();
          }
          return $this->frames;
        }

        /**
         * Gets the total duration of this MPEG audio in seconds
         * @return double
         */
        public function getTotalDuration() {
          if ($this->getFrameCounts()) {
            return $this->duration;
          }
          return 0.0;
        }

        /**

         * Gets a MpegAudioFrameHeader object reperesenting the header of an MPEG audio frame, or false or failure
         * @param int $index
         * @return bool|\falahati\PHPMP3\MpegAudioFrameHeader
         */
        public function getFrameHeader($index) {
          if ($index >= && $index $this->getFrameCounts()) {
            return $this->readFrameHeader($this->frameOffsetTable[$index]);
          }
          return false;
        }

        /**

         * Gets a frame's data (including header) as a binary string, or false or failure
         * @param int $index
         * @return bool|string
         */
        public function getFrameData($index) {
          $frameHeader $this->getFrameHeader($index);
          if ($frameHeader !== false) {
            return $this->read($frameHeader->getOffset(), $frameHeader->
getLength());
          }
          return false;
        }

        /**
         * Removes a set of frames from this MPEG audio, returns this object
         * @param int $index
         * @param int $count
         * @return \falahati\PHPMP3\MpegAudio
         */
        public function removeFrame($index$count 1) {
          if ($count 0) {
            $index += $count;
            $count *= -1;
          }
          if ($index || $index >= $this->getFrameCounts()) {
            return $this;
          }
          $count min($this->getFrameCounts() - $index$count);
          if ($count == 0) {
            return $this;
          }
          $firstFrameHeader $this->getFrameHeader($index);
          $lastFrameHeader $this->getFrameHeader($index + ($count 1));
          $this->slice(($lastFrameHeader->getOffset() + $lastFrameHeader->
getLength()) - $firstFrameHeader->getOffset(), $firstFrameHeader->getOffset());
          $this->reset();
          return $this;
        }

        /**

         * Appends a potion of a MPEG audio to this MPEG audio, returns this object
         * @param \falahati\PHPMP3\MpegAudio $srcAudio
         * @param int $index
         * @param int $length
         * @return \falahati\PHPMP3\MpegAudio
         */
        public function append(\falahati\PHPMP3\MpegAudio $srcAudio$index 0,
 $length = -1) {
          if ($index || $index >= $srcAudio->getFrameCounts()) {
            return $this;
          }
          if ($length 0) {
            $length $srcAudio->getFrameCounts() - $index;
          }
          $length min($srcAudio->getFrameCounts() - $index$length);

          $srcFirstFrameHeader $srcAudio->getFrameHeader($index);
          $srcLastFrameHeader $srcAudio->getFrameHeader($index + ($length 1)
);
          $data $srcAudio->read(($srcLastFrameHeader->getOffset() + 
$srcLastFrameHeader->getLength()) - $srcFirstFrameHeader->getOffset(), 
$srcFirstFrameHeader->getOffset());
          if ($data) {
            $endOfStream 0;
            if ($this->getFrameCounts() > 0) {
              $frameHeader $this->getFrameHeader($this->getFrameCounts() - 1);
              if ($frameHeader !== false) {
                $endOfStream $frameHeader->getOffset() + $frameHeader->
getLength();
              }
            }
            $this->insert($data$endOfStream);
          }
          return $this;
        }

        /**

         * Trims this MPEG audio by removing all frames except the parts that are selected by time in seconds, returns this object
         * @param int $startTime
         * @param int $duration
         * @return \falahati\PHPMP3\MpegAudio
         */
        public function trim($startTime$duration 0) {
          if ($startTime 0) {
            $startTime $this->getTotalDuration() + $startTime;
          }
          if ($duration <= 0) {
            $duration $this->getTotalDuration() - $startTime;
          }
          $endTime min($startTime $duration$this->getTotalDuration());
          $startIndex 0;
          $endIndex 0;
          foreach ($this->frameTimingTable as $frameIndex => $frameTiming) {
            if ($frameTimin<= $startTime) {
              $startIndex $frameIndex;
            } else if ($frameTimin>= $endTime) {
              $endIndex $frameIndex;
              break;
            }
          }
          $this->removeFrame($endIndex$this->getFrameCounts() - $endIndex);
          $this->removeFrame(0$startIndex);
          return $this;
        }

        /**

         * Gets metadata stored at the begining of the MPEG audio as a binary string, or false on failure
         * @return bool|string
         */
        public function getBeginingTags() {
          $start $this->getStart();
          if ($start === false) {
            return false;
          }
          return $this->read($start0);
        }

        /**

         * Gets metadata stored at the end of the MPEG audio as a binary string, or false on failure
         * @return bool|string
         */
        public function getEndingTags() {
          $frames $this->getFrameCounts();
          if ($frames === 0) {
            return false;
          }
          $frame $this->getFrameHeader($frames 1);
          if ($frame === false) {
            return false;
          }
          return $this->read(0$frame->getOffset() + $frame->getLength());
        }

        /**

         * Removes metadata stored at the begining and the end of the MPEG audio, returns this object
         * @return \falahati\PHPMP3\MpegAudio
         */
        public function stripTags() {
          $frames $this->getFrameCounts();
          if ($frames 0) {
            $frame $this->getFrameHeader($frames 1);
            if ($frame !== false) {
              $this->slice(0$frame->getOffset() + $frame->getLength());
            }
          }
          $start $this->getStart();
          if ($start !== false && $start 0) {
            $this->slice($start0);
          }
          $this->reset();
          return $this;
        }
      }

?>


Exemple :

 
 01    
 02    
 03    
 04    
 05    
 06    
 07    
 08    
 09    
 10    
 11    
 12    
 13    
 14    
                                
<?php

    // Supprime les tags ID3 d'un fichier MP3 si ils existent
    MpegAudio::fromFile("01.MP3")->stripTags()->saveFile("new.mp3");
    
    // Durée totale du fichier MP3 :
    echo  MpegAudio::fromFile("01.MP3")->getTotalDuration();

    
// Coupe un fichier MP3 pour extraire 30 secondes à partir de la 10e seconde:
    MpegAudio::fromFile("01.MP3")->trim(1030)->saveFile("new.mp3");
?>

          Fonctions du code - Doc officielle PHP

   php.net   Description Versions PHP OUTIL
   array Crée un tableau PHP 4, PHP 5, PHP 7, PHP 8
   chr Retourne un caractère spécifique PHP 4, PHP 5, PHP 7, PHP 8
   count Compte le nombre d'éléments d'un tableau ou le nombre de propriétés d'un objet PHP 4, PHP 5, PHP 7, PHP 8
   echo Affiche une chaîne de caractères PHP 4, PHP 5, PHP 7, PHP 8
   fclose Ferme un fichier PHP 4, PHP 5, PHP 7, PHP 8
   fflush Envoie tout le contenu généré dans un fichier - (PHP 4 >= 4.0.1, PHP 5, PHP 7) PHP 4, PHP 5, PHP 7, PHP 8
   file_get_contents Lit tout un fichier dans une chaîne - (PHP 4 >= 4.3.0, PHP 5, PHP 7) PHP 4, PHP 5, PHP 7, PHP 8
   file_put_contents Ecrit une chaîne dans un fichier - (PHP 5) PHP 5, PHP 7, PHP 8
   floor Arrondit à l'entier inférieur PHP 4, PHP 5, PHP 7, PHP 8
   is_string Détermine si une variable est de type chaîne de caractères PHP 4, PHP 5, PHP 7, PHP 8
   max La plus grande valeur PHP 4, PHP 5, PHP 7, PHP 8
   min La plus petite valeur PHP 4, PHP 5, PHP 7, PHP 8
   return Retourne le controle du programme au module appelant. PHP 4, PHP 5, PHP 7, PHP 8
   sprintf Retourne une chaîne formatée PHP 4, PHP 5, PHP 7, PHP 8
   strlen Calcule la taille d'une chaîne PHP 4, PHP 5, PHP 7, PHP 8
   substr Retourne un segment de chaîne PHP 4, PHP 5, PHP 7, PHP 8
   unset Détruit une variable PHP 4, PHP 5, PHP 7, PHP 8

   Dites merci aux auteurs pour leurs travail, ça ne coûte rien et ça fait toujours plaisir wink

[1]

  • avatar

    Invité

    30 Nov 2021 à 19:34

    Merci beaucoup !

Présentation de PHP

PHP débutant et initié 50 Tutoriel

Présentation de MySQL

avatar

Place de la Musique

  20 Jan 2020

  SOURCE   Télécharger

Information sur les mises à jour

Dernière mise à jour :

    20 Jan 2020
    fonctionnement du code vérifié

2 812 Vues
Compatibilité
PHP 5, 7 et 8+