如何玩Wav文件

时间:2013-02-19 06:55:40

标签: ios avaudioplayer wav

以下是我的代码 我无法播放SnareHitSample.wav文件。 我不知道我哪里出错了。

-(void)playAudioFiles
{
    NSString * path;
    AVAudioPlayer * snd;
    NSError * err;
    NSString *name;
    name = @"SnareHitSample.wav";
    path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:name];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSURL * url = [NSURL fileURLWithPath:path];
        snd = [[AVAudioPlayer alloc] initWithContentsOfURL:url
                                                      error:&err] ;
        if (! snd) {
            NSLog(@"Sound named '%@' had error %@", name, [err localizedDescription]);
        } else {
            [snd prepareToPlay];
        }
    } else {
        NSLog(@"Sound file '%@' doesn't exist at '%@'", name, path);
    }
}

3 个答案:

答案 0 :(得分:6)

谢谢大家,我在.h文件中声明了avaudioplayer对象,我的问题得到了解决。

  {
 AVAudioPlayer *player1;
  }

答案 1 :(得分:5)

试试这段代码。

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                     pathForResource:@"SnareHitSample"
                                     ofType:@"wav"]];
NSError *error = nil;
AVAudioPlayer * audioPlayer = [[AVAudioPlayer alloc]
               initWithContentsOfURL:url
               error:&error];
if (error)
{
  NSLog(@"Error in audioPlayer: %@",[error localizedDescription]);
}
else
{
    audioPlayer.delegate = self;
    [audioPlayer play];
    [audioPlayer setNumberOfLoops:INT32_MAX]; // for continuous play
}

答案 2 :(得分:1)

尝试以下代码:

AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                                                                      pathForResource:@"SnareHitSample" ofType:@"wav"]] error:NULL];
       [theAudio play];

你将摆脱这个..任何查询都会让我感动..