如何用AVAudioPlayer播放声音?

时间:2012-07-14 10:30:03

标签: objective-c ios avaudioplayer

我是初学者iPhone开发者。我想播放声音,但音频文件返回空值。

这是我的代码:

-(IBAction)sound
{

    path=[[NSBundle mainBundle] pathForResource:@"Animalfile" ofType:@"plist"];
    dict=[NSDictionary dictionaryWithContentsOfFile:path];

    animalaudio=[dict valueForKey:@"audio"];
    NSLog(@"print:%@",dict);
    NSLog(@"printanimal%@",animalaudio);

    audiolist=[animalaudio objectAtIndex:currentsound];
    NSLog(@"audiolist:%@",audiolist);
    NSURL *audiourl=[NSURL fileURLWithPath:audiolist];
    NSLog(@"audiourl:%@",audiourl);

    AVAudioPlayer *audio=[[AVAudioPlayer alloc]initWithContentsOfURL:audiourl error:NULL];
    NSLog(@"audio:%@",audio);
    audio.delegate=self;
    [audio play];
}

音频返回null ...提供适用于我们代码的任何建议和源代码。

1 个答案:

答案 0 :(得分:0)

-(void)primeAudioPlayerWrong {
    NSError *error;
    AVAudioPlayer *audioPlayer;
    if(!audioPlayerWrong){
        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/wrong.mp3", [[NSBundle mainBundle] resourcePath]]];
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    }
    [audioPlayer stop];
    [audioPlayer setCurrentTime:0];
    [audioPlayer play];
}

试试这个......但在此之前,请确保file_url是正确的,并且在提供的网址上存在一些资源......