使用AVAudioPlayer播放音频时出错

时间:2011-07-08 05:46:32

标签: iphone cocoa-touch ios4 avaudioplayer

我在播放音频时遇到错误。 这是不播放录音的原因吗?

Error '!obj' trying to fetch default input device's sample rate
    Error getting audio input device sample rate: '!obj'

- (void)record{    

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }

    recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

    [recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

    NSString *fileName = nil;
    if(![myItem audioURL]){
        fileName = [fileFormatter stringFromDate:[NSDate date]];
        [myItem setAudioURL:fileName];
        NSLog(@"file name :%@",fileName);
        NSLog(@"audio url: %@",[myItem audioURL]);

    } else{
        fileName = [myItem audioURL];}

    NSString *pathString = [NSString stringWithFormat:@"%@/%@", [delegate applicationDocumentsDirectory], fileName];

    recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:pathString] settings:recordSetting error:&err];

    // Create a new dated file
    //NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
   // NSString *caldate = [now description];
  //  recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];

 //   NSURL *url = [NSURL fileURLWithPath:recorderFilePath];


    if(!recorder){
        NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: [err localizedDescription]
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }

    //prepare to record
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;

    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        UIAlertView *cantRecordAlert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: @"Audio input hardware not available"
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [cantRecordAlert show];
        [cantRecordAlert release]; 
        return;
    }

    // start recording
    [recorder recordForDuration:(NSTimeInterval) 10];


        recording = YES;

    [pauseButton setImage:[UIImage imageNamed:@"stop.png"] forState:UIControlStateNormal];
    [pauseButton setEnabled:YES];
    [playButton setEnabled:NO];
    [recordButton setEnabled:NO];


    [self beginAnimation];
    //    NSError *error=nil;
    //    if(![context save: &error])
    //    {
    //        //Couldn't save
    //    }
}





- (void)play{         
            NSString *fileName = nil;
        if(![myItem audioURL]){
            return;
        } else
            fileName = [myItem audioURL];
        NSLog(@"file name :%@",fileName);


        NSString *pathString = [NSString stringWithFormat:@"%@/%@", [delegate applicationDocumentsDirectory], fileName];
        NSLog(@"Path : %@",pathString);


        player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL UrlwithString:pathString] error:nil] ;


    //    if (player==nil) {
    //        NSLog(@"%@",[error description]);
    //    }
    //    else
    //    {
            player.volume=1.0;
            NSLog(@"about to play");
            [player prepareToPlay];
            [player play];
            NSLog(@"player play");
            [player setDelegate:self];
            playing = YES;  

            [recordButton setEnabled:NO];
            [pauseButton setEnabled:YES];
            [playButton setEnabled:NO];


            [self beginAnimation];
       // }
    }

2 个答案:

答案 0 :(得分:3)

尝试使用此代码,

NSURL *url=[NSURL URLWithString:appDelegate.songName];
            NSLog(@"SongURL :%@",url);

            NSData *soundData = [NSData dataWithContentsOfURL:url];


            appDelegate.player = [[AVAudioPlayer alloc] initWithData:soundData error: nil];         
            appDelegate.player.delegate = self;
            appDelegate.player.volume=1.0;  

            // Play the audio
            [appDelegate.player prepareToPlay];             
            [appDelegate.player play];  

这对你有帮助。

并添加FRameworks和headerfiles(AVFoundation.framework和AVToolbox.framework)

答案 1 :(得分:2)

您可以使用此代码播放声音:

 NSString *path = [[NSBundle mainBundle] pathForResource:@"adriantnt_release_click" ofType:@"mp3"];

NSURL *url = [NSURL URLWithString:path];

NSData *data = [NSData dataWithContentsOfURL:url];


AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithData:data error: nil];
theAudio.delegate = self;
theAudio.volume=1.0;

// Play the audio
[theAudio prepareToPlay];
[theAudio play];