简体   繁体   中英

AVAudioPlayer doesn't play audio

I am trying to play a mp3 file but not playing. There is no error. Just not playing.

I've imported necessary files:

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

And this is my code:

NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *soundFilePath = [NSString stringWithFormat:@"%@/music.mp3", documentsDirectory];

    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
    player.numberOfLoops = -1; //Infinite
    player.volume=1;
    player.delegate=self;
    [player prepareToPlay];
    [player play];

Nothing is wrong with mp3 file. I can play it on my iPhone's player but not playing on my app.

One of things you have to watch out for with AVAudioPlayer is that if it has to remain allocated while playing. If you make AVAudioPlayer *player an ivar I think your problem will go away.

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