如何将歌曲从iPod库复制到应用程序并使用AVAudioPlayer播放?

DSh*_*hah 3 iphone audio objective-c avaudioplayer ios

虽然重复,但我想用AVAudioPlayeriPod库播放歌曲.那么将iPod Library歌曲复制到应用程序后是否可以复制?

我有一个代码将歌曲转换为caf格式,然后我可以使用AVAudioPlayer.但转换需要很长时间.那么我能做到这一点吗?

Dan*_*iel 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];



    }
Run Code Online (Sandbox Code Playgroud)