2012-09-21 56 views
2

我发现(自定义我找到的方法)一种方法来转换MpMediaItem并获取mp3文件。可能这不是最好的方式,但它的工作。objective c - 将mpmediaitem转换为ogg vorbis

有没有办法获得* .ogg文件而不是* .mp3?什么是正确的方法?

这是我使用来获取* .MP3文件的方法:

-(void)exportMP3:(NSURL*)url toFileUrl:(NSString*)fileURL 
{ 
    AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil]; 
    AVAssetReader *reader=[[AVAssetReader alloc] initWithAsset:asset error:nil]; 
    NSMutableArray *myOutputs =[[NSMutableArray alloc] init]; 
    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] attributes:nil]; 
    }else{ 
     NSURL *url = [NSURL URLWithString:fileURL]; 
     [fm removeItemAtURL:url error:nil]; 
     [fm createFileAtPath:fileURL contents:[[NSData alloc] init] attributes:nil]; 

    } 
    fileHandle=[NSFileHandle fileHandleForWritingAtPath:fileURL];  
    [fileHandle seekToEndOfFile]; 

    AVAssetReaderOutput *output=[myOutputs objectAtIndex:0]; 
    int totalBuff=0; 
    int test = 1; 
    while(test == 1) 
    { 
     CMSampleBufferRef ref=[output copyNextSampleBuffer]; 

     if(ref==NULL) 
      test = 0; 

     if(ref==NULL) 
      break; 
     //copy data to file 
     //read next one 
     AudioBufferList audioBufferList; 
     NSMutableData *data; 
     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]; 
      void *frame = audioBuffer.mData; 

      data = [[NSMutableData alloc] initWithBytes:frame length:audioBuffer.mDataByteSize]; 
     } 
     totalBuff++; 
     NSLog(@"\n%d\n",totalBuff); 

     int time = [self.mediaPlayer durationOfCurrentItem]; 

     if (totalBuff * 2 <= time + 1)   
      [fileHandle writeData:data]; 

    } 
    [fileHandle closeFile]; 
} 
+0

如果你的编码MP3编码正常工作,这将是一个重大突破,因为它是一个普遍接受的事实,没有像[跛脚](http://lame.sourceforge.net/)第三方库,它是不可能在ios中将音频编码成MP3格式。你确定这是有效的,而不是简单地播放,因为一个音频播放器,它接受一个MP3文件内的其他格式的善意? –

回答

3

您可以使用libvorbis到PCM数据编码到Vorbis格式。

+0

需要多长时间才能获得平均mp3的ogg文件?假设mp3歌曲长约3分钟。我用来获取mp3文件的方法有时需要2秒。我担心滞后。谢谢 – bursyllac

+0

@SylBurlac媒体转换的计算成本很高。您应该在后台线程中执行此操作。 – 2012-09-21 08:32:16

+0

我是在后台线程中完成的,但转换是在我点击播放按钮时开始的(我使用它将dlna流式传输到仅支持ogg格式的设备),我很担心点击播放按钮之间的时间间隔以及直到设备开始播放的时间间隔。非常感谢您的回答 – bursyllac