2011-09-19 62 views

回答

6

下面的代碼將從其url中讀取ipod庫歌曲並將其複製到磁盤以供使用。 請注意,此代碼不適用於m4as,因爲ipod庫中的m4as URL不包含標頭,因此您需要使用AVAssetExporter編寫標頭和音樂數據到磁盤。

-(void)exportMP3:(NSURL*)url toFileUrl:(NSString*)fileURL 
    { 
     AVURLAsset *asset=[[[AVURLAsset alloc] initWithURL:url options:nil] autorelease]; 
     AVAssetReader *reader=[[[AVAssetReader alloc] initWithAsset:asset error:nil] autorelease]; 
     NSMutableArray *myOutputs =[[[NSMutableArray alloc] init] autorelease]; 
     for(id track in [asset tracks]) 
     { 
      AVAssetReaderTrackOutput *output=[AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:track outputSettings:nil]; 
      [myOutputs addObject:output]; 
      [reader addOutput:output]; 
     } 
     [reader startReading]; 
     NSFileHandle *fileHandle ; 
     NSFileManager *fm=[NSFileManager defaultManager]; 
     if(![fm fileExistsAtPath:fileURL]) 
     { 
      [fm createFileAtPath:fileURL contents:[[[NSData alloc] init] autorelease] attributes:nil]; 
     } 
     fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:fileURL];  
     [fileHandle seekToEndOfFile]; 

     AVAssetReaderOutput *output=[myOutputs objectAtIndex:0]; 
     int totalBuff=0; 
     while(TRUE) 
     { 
      CMSampleBufferRef ref=[output copyNextSampleBuffer]; 
      if(ref==NULL) 
       break; 
      //copy data to file 
      //read next one 
      AudioBufferList audioBufferList; 
      NSMutableData *data=[[NSMutableData alloc] init]; 
      CMBlockBufferRef blockBuffer; 
      CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(ref, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer); 

      for(int y=0; y<audioBufferList.mNumberBuffers; y++) 
      { 
       AudioBuffer audioBuffer = audioBufferList.mBuffers[y]; 
       Float32 *frame = audioBuffer.mData; 


       // Float32 currentSample = frame[i]; 
       [data appendBytes:frame length:audioBuffer.mDataByteSize]; 

       // written= fwrite(frame, sizeof(Float32), audioBuffer.mDataByteSize, f); 
       ////NSLog(@"Wrote %d", written); 

      } 
      totalBuff++; 
      CFRelease(blockBuffer); 
      CFRelease(ref); 
      [fileHandle writeData:data]; 
      // //NSLog(@"writting %d frame for amounts of buffers %d ", data.length, audioBufferList.mNumberBuffers); 
      [data release]; 
     } 
     // //NSLog(@"total buffs %d", totalBuff); 
    // fclose(f); 
     [fileHandle closeFile]; 



    } 
+0

有關使用AVAssetExporter修復m4a文件頭部的任何提示? – bendytree

+0

生成的mp3文件不顯示專輯封面,任何幫助 –

+0

@James爲什麼會這樣?您正在複製音樂字節而不是專輯封面... – Daniel

相關問題