Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Google Sign In with OpenID

Export audio as M4A (ALAC)

AnotherAnother Posts: 3New Users
edited March 2012 in iPhone SDK Development
Hi! Is this possible to export audio from iPod library as M4A (ALAC)?

How I can export as WAV and as source format.

- (IBAction)saveAsSourceFormat {
	[self exportAssetAsSourceFormat:song];
	};

- (IBAction)saveAsWaveFormat {
	[self exportAssetAsWaveFormat:song];
	};

- (IBAction)saveAsM4aFormat {
	[self exportAssetAsM4aFormat:song];
	};

- (void)exportAssetAsSourceFormat:(MPMediaItem *)item {
	
	NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];	
	AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
	
	// JP
	AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
                                           initWithAsset:songAsset
                                           presetName:AVAssetExportPresetPassthrough];
	
	NSArray *tracks = [songAsset tracksWithMediaType:AVMediaTypeAudio];
	AVAssetTrack *track = [tracks objectAtIndex:0];
	id desc = [track.formatDescriptions objectAtIndex:0];
	const AudioStreamBasicDescription *audioDesc = CMAudioFormatDescriptionGetStreamBasicDescription((CMAudioFormatDescriptionRef)desc);
    FourCharCode formatID = audioDesc->mFormatID;
	
	//exportAudioMix.inputParameters = [NSArray arrayWithObject:exportAudioMixInputParameters];	
	//exportSession.audioMix = exportAudioMix;
		
	NSString *fileType = nil;
	NSString *ex = nil;
	
	switch (formatID) {
            
        case kAudioFormatLinearPCM:
        {
            UInt32 flags = audioDesc->mFormatFlags;
            if (flags & kAudioFormatFlagIsBigEndian) {
                fileType = @"public.aiff-audio";
                ex = @"aif";
            } else {
                fileType = @"com.microsoft.waveform-audio";
                ex = @"wav";
            }
        }
            break;
            
        case kAudioFormatMPEGLayer3:
            fileType = @"com.apple.quicktime-movie";
            ex = @"mp3";
			break;
            
        case kAudioFormatMPEG4AAC:
            fileType = @"com.apple.m4a-audio";
            ex = @"m4a";
            break;
            
        case kAudioFormatAppleLossless:
            fileType = @"com.apple.m4a-audio";
            ex = @"m4a";
            break;
            
        default:
            break;
    }
	
	exportSession.outputFileType = fileType;
	
	// filename 
	NSString *fileName = nil;
	
	fileName = [NSString stringWithString:[song valueForProperty:MPMediaItemPropertyTitle]];
	fileName = [[fileName stringByAppendingString:@"-"] stringByAppendingString:[song valueForProperty:MPMediaItemPropertyArtist]];
	NSArray *fileNameArray = nil;
	fileNameArray = [fileName componentsSeparatedByString:@" "];
	fileName = [fileNameArray componentsJoinedByString:@""];
	
	NSLog(@"fileName = %@", fileName);
	
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [[docDir stringByAppendingPathComponent:fileName] stringByAppendingPathExtension:ex];
	
	
	// -------------------------------------
	int fileNumber = 0;
	NSString *fileNumberString = nil;
	NSString *fileNameWithNumber = nil;
	while ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		fileNumber++;
		fileNumberString = [NSString stringWithFormat:@"-%02d", fileNumber];
		fileNameWithNumber = [fileName stringByAppendingString:fileNumberString];
		filePath = [[docDir stringByAppendingPathComponent:fileNameWithNumber] stringByAppendingPathExtension:ex];
		NSLog(@"filePath = %@", filePath);		
	}	
	
	// -------------------------------------
	
	
    myDeleteFile(filePath);
	exportSession.outputURL = [NSURL fileURLWithPath:filePath];
    
	
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        
        if (exportSession.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"export session completed");
			/*
			 // load "Save" view
			 UIViewController *saveViewController = [[SaveViewController alloc] initWithNibName:@"Save" bundle:[NSBundle mainBundle]];
			 NSLog(@"before");
			 [self.navigationController pushViewController:saveViewController animated:NO];
			 NSLog(@"after");
			 [saveViewController release];	
			 */
			//
			//return YES;
        } else {
            NSLog(@"export session error");
			//return NO;
        }
        
        [exportSession release];
    }];
}


void myDeleteFile (NSString* path) {
	if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
		NSError *deleteErr = nil;
		[[NSFileManager defaultManager] removeItemAtPath:path error:&deleteErr];
		if (deleteErr) {
			NSLog (@"Can't delete %@: %@", path, deleteErr);
		}
	}
}

- (BOOL)exportAssetAsWaveFormat:(MPMediaItem *)item {
	//-------------------------------------------
	
	NSError *error = nil;
    
	// .wav
    NSDictionary *audioSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat:44100.0],AVSampleRateKey,
                                  [NSNumber numberWithInt:2],AVNumberOfChannelsKey,
                                  [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                  [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
                                  [NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey, 
                                  [NSNumber numberWithBool:0], AVLinearPCMIsBigEndianKey,
                                  [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
                                  [NSData data], AVChannelLayoutKey, nil];
	
	
	/*
	 // .m4a
	 NSDictionary *audioSetting = [NSDictionary dictionaryWithObjectsAndKeys:
	 [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
	 [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
	 [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
	 [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
	 nil];
	 */
	
    
    //読み込み側のセットアップ
    
    NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
    AVURLAsset *URLAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    if (!URLAsset) return NO;
    
    AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:URLAsset error:&error];
    if (error) return NO;
    
    NSArray *tracks = [URLAsset tracksWithMediaType:AVMediaTypeAudio];
    if (![tracks count]) return NO;
    
    AVAssetReaderAudioMixOutput *audioMixOutput = [AVAssetReaderAudioMixOutput
                                                   assetReaderAudioMixOutputWithAudioTracks:tracks
                                                   audioSettings:audioSetting];
    
    if (![assetReader canAddOutput:audioMixOutput]) return NO;
    
    [assetReader addOutput:audioMixOutput];
    
    if (![assetReader startReading]) return NO;
    
    
    //書き込み側のセットアップ
    
    NSString *title = [item valueForProperty:MPMediaItemPropertyTitle];
    NSArray *docDirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [docDirs objectAtIndex:0];
    NSString *outPath = [[docDir stringByAppendingPathComponent:title]
                         stringByAppendingPathExtension:@"wav"];
    
    NSURL *outURL = [NSURL fileURLWithPath:outPath];
    AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:outURL
                                                          fileType:AVFileTypeWAVE
                                                             error:&error];
    if (error) return NO;
    
    AVAssetWriterInput *assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio
                                                                              outputSettings:audioSetting];
    assetWriterInput.expectsMediaDataInRealTime = NO;
    
    if (![assetWriter canAddInput:assetWriterInput]) return NO;
    
    [assetWriter addInput:assetWriterInput];
    
    if (![assetWriter startWriting]) return NO;
    
    
    
    //コピー処理
    
    [assetReader retain];
    [assetWriter retain];
    
    [assetWriter startSessionAtSourceTime:kCMTimeZero];
    
    dispatch_queue_t queue = dispatch_queue_create("assetWriterQueue", NULL);
    
    [assetWriterInput requestMediaDataWhenReadyOnQueue:queue usingBlock:^{
        
        NSLog(@"start");
        
        while (1)
        {
            if ([assetWriterInput isReadyForMoreMediaData]) {
                
                CMSampleBufferRef sampleBuffer = [audioMixOutput copyNextSampleBuffer];
                
                if (sampleBuffer) {
                    [assetWriterInput appendSampleBuffer:sampleBuffer];
                    CFRelease(sampleBuffer);
                } else {
                    [assetWriterInput markAsFinished];
                    break;
                }
            }
        }
        
        [assetWriter finishWriting];
        [assetReader release];
        [assetWriter release];
        
        NSLog(@"finish");
    }];
    
    dispatch_release(queue);
}

- (BOOL)exportAssetAsM4aFormat:(MPMediaItem *)item {
	// Please help!!!!
}


Post edited by Another on

Replies

Sign In or Register to comment.