Friday, 29 May 2015

How to clip an audio file in iPhone?

Here is the method in ios that can clip an audio file(i.e MPMediaItem) with the time interval.
In below mentioned method, For time interval we are sending two parameter first is startinterval which is the interval form where we wanted to start clipping the audio file and another parameter is totalTimeInterval which is for the duration till where we need the audio to be clipped and the url path of the audio clipped will be retrieved in the block.
  1. -(void)convertAudioFileWithFile:(MPMediaItem *)song startInterval:(NSTimeInterval)startinterval
  2. totalTimeInterval:(NSTimeInterval)totalTimeInterval
  3. completion:(void(^)(NSString *urlString))callback{
  4. // set up an AVAssetReader to read from the iPod Library
  5. NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
  6. AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
  7. NSError *assetError = nil;
  8. AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:songAsset
  9. error:&assetError]
  10. ;
  11. // set the interval
  12. CMTime start = songAsset.duration;
  13. CMTime end = songAsset.duration;
  14. start.value = start.timescale*startinterval;
  15. end.value = end.timescale*totalTimeInterval;
  16. [assetReader setTimeRange:CMTimeRangeMake(start, end)];
  17. ///////
  18. if (assetError) {
  19. NSLog (@"error: %@", assetError);
  20. return;
  21. }
  22. AVAssetReaderOutput *assetReaderOutput = [AVAssetReaderAudioMixOutput
  23. assetReaderAudioMixOutputWithAudioTracks:songAsset.tracks
  24. audioSettings: nil]
  25. ;
  26. if (! [assetReader canAddOutput: assetReaderOutput]) {
  27. NSLog (@"can't add reader output... die!");
  28. return;
  29. }
  30. [assetReader addOutput: assetReaderOutput];
  31. NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  32. NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
  33. NSString *exportPath = [documentsDirectoryPath stringByAppendingPathComponent:EXPORT_NAME];
  34. if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
  35. [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
  36. }
  37. NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
  38. AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:exportURL
  39. fileType:AVFileTypeCoreAudioFormat
  40. error:&assetError];
  41. if (assetError) {
  42. NSLog (@"error: %@", assetError);
  43. return;
  44. }
  45. NSNumber *sampleRate = [NSNumber numberWithInt:12000.0];//[NSNumber numberWithFloat:44100.0]
  46. AudioChannelLayout channelLayout;
  47. memset(&channelLayout, 0, sizeof(AudioChannelLayout));
  48. channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
  49. NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
  50. [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
  51. sampleRate, AVSampleRateKey,
  52. [NSNumber numberWithInt:1], AVNumberOfChannelsKey,
  53. [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey,
  54. [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
  55. [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
  56. [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
  57. [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
  58. nil];
  59. AVAssetWriterInput *assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio
  60. outputSettings:outputSettings]
  61. ;
  62. if ([assetWriter canAddInput:assetWriterInput]) {
  63. [assetWriter addInput:assetWriterInput];
  64. } else {
  65. NSLog (@"can't add asset writer input... die!");
  66. return;
  67. }
  68. assetWriterInput.expectsMediaDataInRealTime = NO;
  69. [assetWriter startWriting];
  70. [assetReader startReading];
  71. AVAssetTrack *soundTrack = [songAsset.tracks objectAtIndex:0];
  72. CMTime startTime = CMTimeMake (0, soundTrack.naturalTimeScale);
  73. [assetWriter startSessionAtSourceTime: startTime];
  74. __block UInt64 convertedByteCount = 0;
  75. dispatch_queue_t mediaInputQueue = dispatch_queue_create("mediaInputQueue", NULL);
  76. [assetWriterInput requestMediaDataWhenReadyOnQueue:mediaInputQueue
  77. usingBlock: ^
  78. {
  79. // NSLog (@"top of block");
  80. while (assetWriterInput.readyForMoreMediaData) {
  81. CMSampleBufferRef nextBuffer = [assetReaderOutput copyNextSampleBuffer];
  82. if (nextBuffer) {
  83. // append buffer
  84. [assetWriterInput appendSampleBuffer: nextBuffer];
  85. // NSLog (@"appended a buffer (%d bytes)",
  86. // CMSampleBufferGetTotalSampleSize (nextBuffer));
  87. convertedByteCount += CMSampleBufferGetTotalSampleSize (nextBuffer);
  88. // oops, no
  89. // sizeLabel.text = [NSString stringWithFormat: @"%ld bytes converted", convertedByteCount];
  90. // NSNumber *convertedByteCountNumber = [NSNumber numberWithLong:convertedByteCount];
  91. // [self performSelectorOnMainThread:@selector(updateSizeLabel:)
  92. // withObject:convertedByteCountNumber
  93. // waitUntilDone:NO];
  94. } else {
  95. // done!
  96. [assetWriterInput markAsFinished];
  97. [assetWriter finishWritingWithCompletionHandler:^{
  98. // callback(exportPath);
  99. }];
  100. callback(exportPath);
  101. [assetReader cancelReading];
  102. NSDictionary *outputFileAttributes = [[NSFileManager defaultManager]
  103. attributesOfItemAtPath:exportPath
  104. error:nil];
  105. NSLog (@"done. file size is %llu",
  106. [outputFileAttributes fileSize]);
  107. // release a lot of stuff
  108. [assetReader release];
  109. [assetReaderOutput release];
  110. [assetWriter release];
  111. [assetWriterInput release];
  112. [exportPath release];
  113. break;
  114. }
  115. }
  116. }];
  117. NSLog (@"bottom of convertTapped:");
  118. }

For such more Blogs you can visit to http://findnerd.com/NerdDigest

No comments:

Post a Comment