简体   繁体   中英

How to play a sound with AVAudioPlayer?

I'm a beginner iPhone developer. I want to play sound but the audio file returns a null value.

This is my code:

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

Audio returns null... Give any suggestion and source code which apply in our code.

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

try this... but before this, make sure that the file_url is correct and there exist some resource at the provided url...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM