在iOS中播放一首歌

时间:2014-03-13 16:03:32

标签: ios objective-c avaudioplayer audio-player

我试图在iOS上播放一首歌,但它给了我一条错误信息。

HEADER FILE .h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface PRPViewController : UIViewController{
    AVAudioPlayer *audioPlayer;
    IBOutlet UIButton *start;
}

-(IBAction)play;

@end

实施文件.m

NSURL *url = [NSURL fileURLWithPath:
                 [NSString stringWithFormat:@"%@/bobmarley.mp3",          
                     [[NSBundle mainBundle] resourcePath]]];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsofURL:url error:&error];
audioPlayer.numberOfLoops = 0;

[audioPlayer play];

但它说

  

AVAudioPlayer没有可见的@interface声明选择器&#39; initWithContentsofUrl:错误:&#39;

我该怎么办?

2 个答案:

答案 0 :(得分:2)

你应该利用&#34; O&#34;在Of。在Objective-C中,拼写计数,包括大写。 initWithContentsofURLinitWithContentsOfURL是两回事。

(顺便说一句,这是尽可能多地使用自动完成的一个很好的理由。自动完成机制比你如何拼写声明方法的名称要好得多!)

答案 1 :(得分:0)

您应该使用方法initWithContentsOfURL检查系统上的文件是否可用,您的错误是错误的。否则应用程序可能崩溃。我创建了一个为我处理一切的类:

@implementation AudioPlayer{

    AVAudioPlayer *_sound;
    NSURL *_soundURL;
    NSString *_receivedValue;

    float _volumeSpecific;
}

- (id)initWithAudioFile:(NSString *)fileName andExtension:(NSString *)extension{

    self = [super init];
    if( self ){
        _receivedValue = fileName;

        _soundURL = [NSURL fileURLWithPath:
                     [[NSBundle mainBundle] pathForResource:fileName
                                                     ofType:extension]];
        if([[NSFileManager defaultManager] fileExistsAtPath:[_soundURL path]]){
            _sound = [[AVAudioPlayer alloc] initWithContentsOfURL:_soundURL 
                                                            error:nil];
        }
    }

    return self;
}

- (void)playEndless{

    if( [[NSUserDefaults standardUserDefaults] boolForKey:kSound] ){
        _sound.numberOfLoops = -1;
        [_sound play];
    }
}

- (void)setVolume:(float)myVolume{

    _volumeSpecific = myVolume;
    [_sound setVolume:myVolume];
}

- (void)play{
    if( _sound == nil ){
        NSLog(@"No AudioPlayer available %@", self);
    }
    if( [[NSUserDefaults standardUserDefaults] boolForKey:kSound] ){

        if( _volumeSpecific ){
            [_sound setVolume:_volumeSpecific];
        }
        [_sound play];
    }
}

- (NSString *)description{        
    return [NSString stringWithFormat:@"Received: %@, Player: %@, URL: %@",
            _receivedValue, _sound, _soundURL];
}