在 iPhone for iOs 5.0 中从 iPod 库导入歌曲时应用程序崩溃

2023-12-28

你好我正在使用下面的框架,

#import <MediaPlayer/MediaPlayer.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

在按钮事件之一中,我实现了以下代码来打开库。

        MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
    mediaPicker.delegate = self;
    mediaPicker.allowsPickingMultipleItems = YES; // this is the default   
    [self presentModalViewController:mediaPicker animated:YES];
    [mediaPicker release];

在 MPMediaPickerController 的委托方法中实现的代码如下

#pragma mark MPMediaPickerController delegate methods

- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {

    // We need to dismiss the picker
    [self dismissModalViewControllerAnimated:YES];

    // Assign the selected item(s) to the music player and start playback.

    counterIpod = [mediaItemCollection.items count];
    totalcollection = counterIpod;
    if (totalcollection > 10) {
        NSString *str = [NSString stringWithFormat:@"App Only supports importing 10 songs at a time"];
        UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:@"Message !" message:str delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [connectionAlert show];
        [connectionAlert release];
    }
    else {
        [self performSelector:@selector(saveMediaItem:) withObject:mediaItemCollection afterDelay:0.1];
        //[self saveMediaItem:mediaItemCollection];
        //[self showLoadingView];       
    }
}

- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {
    // User did not select anything
    // We need to dismiss the picker
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark Sace Item Collection to documentsDirectory
-(void)saveMediaItem:(MPMediaItemCollection *)mediaItemCollection {

    for (int i = 0; i < [mediaItemCollection.items count]; i++) {

        [self exportAssetAsSourceFormat:[[mediaItemCollection items] objectAtIndex:i]];

        NSLog(@"for loop : %d", i);
    }

    NSArray *itemsArray1 = appDelegate.mediaItemCollection1.items;
    MPMediaItemCollection *mediaItemCollection2;

    if ([itemsArray1 count] != 0) {
        mediaItemCollection2 = [self collectionByAppendingCollection:mediaItemCollection];
    }
    else {
        mediaItemCollection2 = mediaItemCollection;
    }

    [self saveMediaItemAfterDeletting:mediaItemCollection2];
}

-(void)saveMediaItemAfterDeletting:(MPMediaItemCollection *)mediaItemCollection {

    NSMutableData* data = [[NSMutableData alloc] init];

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:mediaItemCollection forKey:@"my_playlist"];
    [archiver finishEncoding];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *filePath = [NSString stringWithFormat:@"%@/playlist.data", documentsDirectory];
    NSLog(@"file path = %@", filePath);

    [data writeToFile:filePath atomically:YES];

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        NSLog(@"file exists : ===========>>>>>>>>>>>");
    } else {
        NSLog(@"file doesn't exist");
    }

    //NSLog(@"archiving playlist success = %d", success);

    [archiver release];
    [data release];

    [self UpdateMediaCollection];
}

-(NSString*) getExtension:(MPMediaItem *)item {

    //  [self showLoadingView];

    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;
    }   

    return ex;

}


#pragma mark Covert Item separate item collection and store songs into directory 
- (void)exportAssetAsSourceFormat:(MPMediaItem *)item {

    //  [self showLoadingView];

    NSLog(@"export asset called");
    NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
    NSLog(@"\n>>>> assetURL : %@",[assetURL absoluteString]);
    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;     

    NSString *fileName = nil;

    fileName = [NSString stringWithString:[item valueForProperty:MPMediaItemPropertyTitle]];
    fileName = [[fileName stringByAppendingString:@"-"] stringByAppendingString:[item 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];

    NSLog(@"filePath = %@", filePath);  

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        //NSLog(@"file exist::::::::::==============>>>>>>>>>>>>>>>>>");
        counterIpod--;

        if(counterIpod == 0) {
            //[self showAlertView];
            //[self hideLoadingView];
        }

        NSString *str = [NSString stringWithFormat:@"Loading %d of %d Beats", totalcollection - counterIpod ,totalcollection];
        [lbl performSelectorOnMainThread:@selector(setText:) withObject:str waitUntilDone:NO];
        //NSLog(@"loading string : %@", str);

        return;
    }

    //NSLog(@"file not exist  ===========>>>>>>>>>");
    // -------------------------------------
    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");
            counterIpod--;

            NSString *str = [NSString stringWithFormat:@"Loading %d of %d Beats", totalcollection - counterIpod ,totalcollection];

            //[self performSelector:@selector(setLabelText:) withObject:str afterDelay:0.02];
            [lbl performSelectorOnMainThread:@selector(setText:) withObject:str waitUntilDone:NO];
            NSLog(@"loading string : %@", str);

            if(counterIpod == 0) {
                //[self showAlertView];
                //[self hideLoadingView];
            }
        } else {
            NSLog(@"export session error");
            counterIpod--;
            NSString *str = [NSString stringWithFormat:@"Loading %d of %d Beats", totalcollection - counterIpod ,totalcollection];
            [lbl performSelectorOnMainThread:@selector(setText:) withObject:str waitUntilDone:NO];
            //return NO;
            if(counterIpod == 0) {
                //[self showAlertView];
                //[self hideLoadingView];
            }
        }

        [exportSession release];
    }];

    //[appDelegate hideLoadingView];
}

#pragma mark method to delete file from document directory 
void myDeleteFile (NSString* path) {
    //  NSLog(@"file path delete file :::::::::: %@", path);
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *deleteErr = nil;
        [[NSFileManager defaultManager] removeItemAtPath:path error:&deleteErr];
        if (deleteErr) {
            NSLog (@"Can't delete %@: %@", path, deleteErr);
        }
    }
}

上面的代码在 iOS 4.0 或之前的版本上运行没有任何错误,但对于 iOS 5.0 在设备上崩溃,自过去 15 天以来我无法解决这些问题。

预先感谢您的帮助。


我已经解决了这个问题,

只需注释掉这一行

 fileName = [[fileName stringByAppendingString:@"-"] stringByAppendingString:[item valueForProperty:MPMediaItemPropertyArtist]];

因为有些歌曲没有艺术家,所以崩溃了............

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 iPhone for iOs 5.0 中从 iPod 库导入歌曲时应用程序崩溃 的相关文章

  • 是什么导致了这个 iPhone 崩溃日志?

    我有点卡住了 需要解决这个问题 因为我的一个应用程序出现了随机崩溃 而这些崩溃并不总是能够重现 这是崩溃日志之一 Incident Identifier 59865612 9F00 44EA 9474 2BF607AD662E CrashR
  • 有什么方法可以让我知道按屏幕的力度有多大

    我想找到触摸的压力 我只是不知道如何在不越狱并获取原始触摸数据的情况下实现该结果 有谁知道我会怎么做 你无法获得来自SDK的压力nor未记录的方法 然而你can使用未记录的方法检测触摸的大小 在 GSEvent UIEvent 的较低级别表
  • 用 UIView 像翻书一样翻页?

    我正在尝试在之间切换UIViews让它看起来就像你正在翻书的一页 The UIViewAnimationTransitionCurlUp如果我能让它向左或向右卷曲 那就非常接近了 这可能吗 我尝试过使用CATRansition但没有一种动画
  • Swift 3:如何去除UITableView屏幕截图的灰色区域

    我在从桌面视图的屏幕截图中删除灰色区域时遇到了问题 这是我尝试截图时的输出UITableView 实际上我隐藏了一些tableViewCell这是不需要的 可能这就是区域显示灰色的原因 任何帮助表示赞赏 非常感谢 Answer 我通过使用
  • 如何将 NSIndexpath 转换为 NSInteger 或简单的 int?

    我需要将 nsindexpath var 转换为 NsInteger 或简单的 int 例如 int rowIndex mGoogleBaseTable selectedRow mGoogleBaseTable is a NSTable t
  • Objective Flickr 照片上传错误

    我正在使用 ObjectiveFlickr 库将照片从我的 iPhone 应用程序上传到 Flickr 我可以授权该应用程序并执行一般请求 但在尝试上传照片时遇到错误 要上传的照片是使用 AVFoundation 捕获的图像 这是相关代码
  • 如何从代码隐藏中设置 CarouselView 的项目?

    我有一个 CarouselView 它绑定到图像的 ItemsSource 但我想通过更改 CarouselView 的索引来更改当前显示的图像 我尝试使用 CarouselView Position 作为必须选择的元素的索引 但不幸的是这
  • PresentModalViewController 不执行任何操作

    我有一个 UIViewController parent 调用presentModalViewController与另一个 UIViewController child on viewDidLoad If parent没有 UINaviga
  • 在后台任务中安排通知

    我正在为 iOS 开发一个日历 闹钟应用程序 它与网络服务器同步 当在服务器上添加活动时 会发出推送通知 以便 iOS 客户端可以获取新数据 并根据需要更新和安排下一次警报的时间 本地通知 但这仅在应用程序在客户端打开时才有效 我希望客户端
  • 使用 Google place API 从 lat long 获取附近的地点

    我正在使用 google place API 即 https maps googleapis com maps api place search json location 33 7167 73 0667 radius 500 type f
  • 如何使用 Swift 获取 YouTube 频道的所有播放列表?

    我的问题不是关于从一般频道检索视频 我只想获取该频道创建的所有 播放列表 并检索每个播放列表的缩略图 标题和视频数量 这是一个 YouTube 频道示例 正如您所看到的 有很多已创建的播放列表 截至目前 我只能获取某个频道最新上传的视频 在
  • PrepareForSegue之谜

    我在两个不同的 VC 中有一个prepareForSegue 方法 一个使用一个if声明 而另一个旨在使用switch 除了名称之外 代码几乎相同 这个效果很好 void prepareForSegue UIStoryboardSegue
  • 重置转换后的 UIView 的原点会变得疯狂

    我使用 UIView transform 旋转 缩放 UIVIew 效果很好 然而 一旦我更改视图的框架原点 即使我没有执行任何进一步的 CGAffineTransforms 视图的内容也会开始 奇怪 地缩放 为什么会出现这种情况 我该如何
  • 对于某些纹理尺寸,glFramebufferTexture2D 在 iPhone 上失败

    当我尝试将纹理附加到帧缓冲区时 glCheckFramebufferStatus 报告某些纹理大小的 GL FRAMEBUFFER UNSUPPORTED 我已经在第二代和第四代 iPod Touch 上进行了测试 两个模型之间失败的纹理尺
  • iOS WKWebView.scrollView委托导致BAD_ACCESS

    我的 viewController 有一个 UIView 属性 其中包含一个 WKWebView 我将 WKWebView rollView 委托设置为我的 viewController 它是我的 UIView 子类的公共函数 并在我的 v
  • 在 Instruments 中查找内存泄漏行

    我是 iOS 中的仪器新手 我正在尝试使用 Xcode 4 5 2 并按照本教程查找仪器中的内存泄漏 http soulwithmobiletechnology blogspot sg 2011 04 how to check memory
  • 自定义 MKAnnotationView - 如何捕获触摸而不忽略标注?

    我有一个自定义 MKAnnotationView 子类 它完全按照我想要的方式显示视图 在那个视图中 我有一个按钮 我想捕获按钮上的事件来执行操作 这很好用 但是 我不希望标注被忽略或消失 基本上 触摸标注中的按钮将开始播放声音 但我想保留
  • xcode 6.1 (Swift) 中的 SIGABRT 运行时错误

    与最初的代码相比 唯一的更改是在ViewControl swift override func viewDidLoad newMessage hidden true super viewDidLoad Do any additional s
  • 我应该在哪个方法中设置 UITextField 的委托?

    在 viewDidLoad 或 init 方法中设置 UITextField 的委托是一个好习惯吗 我尝试在 init 方法中将委托设置为 self 但它没有调用相应的委托方法 当我将代码移动到 viewDidLoad 中时 它注册为将 s
  • 如何获取 UIWebView 中元素的位置?

    我在 iPad 程序中加载了 html 的 UIWebView 通过使用 webkit column width 我将 html 分为几列 padding 0px height 1024px webkit column gap 0px we

随机推荐