简体   繁体   中英

play 15 second mp3 ios

I have tried everything I can find to try and get my app to play an mp3. I have a few 2-3 second mp3s that play as sound effects that work, but I am trying to play a 15s mp3 without any luck.

    NSError *error;
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: @"test" withExtension: @"mp3"] error:&error];
    if (error)  {
        NSLog(@"Error creating audio player: %@", [error userInfo]);
    } else {
        if([audioPlayer play] == FALSE) {
            NSLog(@"Fail %@", error);
        }
    }
    NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 15.0 target: self
                                                      selector: @selector(stopMusic) userInfo: nil repeats: NO];

I doubt the timer has anything to do with it but thought I would include it just in case. Basically my error checks are not getting triggered at all. It "should" be playing properly but no sound is coming out, and no errors are being displayed.

I have tried a few other things to try and get this working, and I have tried without the timer. I can't find a decent guide. I don't need a full blown media player, just some background music for an UIScreenViewController .

I have also tried the following code, which works good with short MP3s, not with the longer MP3 I want to play.

NSString *path  = [[NSBundle mainBundle] pathForResource:@"bgmusic" ofType:@"mp3"];
NSURL *pathURL = [NSURL fileURLWithPath : path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &audioEffect);
AudioServicesPlaySystemSound(audioEffect);

Please help, I have spent hours trying to sort this. It seems apple re-jig their audio every time they release an OS.

I did a little testing for you: It turned out that music files aren't added to target by default in Xcode 5. Therefore URLForResource:error: likely returns nil .

Try removing the mp3 from your project. Then add it again and this time make shure you add it to your target:

Xcode屏幕截图

The other thing is: It seems like you're defining the AVAudioPlayer inside a method. You normally set up a @property for your audio player because otherwise its life is limited to the method - and the music stops playing after you reach the end of the method.

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