2012-10-02 235 views
3

我想播放音频文件,但我可以让它工作。 我导入了AVFoundation框架。如何播放音频文件ios

下面是代码:

NSString *fileName = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"]; 
    NSURL *url = [[NSURL alloc] initFileURLWithPath:fileName]; 
    NSLog(@"Test: %@ ", url); 

    AVAudioPlayer *audioFile = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL]; 
    audioFile.delegate = self; 
    audioFile.volume = 1; 

    [audioFile play]; 

我收到一个错误nil string parameter

我复制该文件到支持文件夹,以便该文件是存在的。

你们能帮我吗?

感谢

+0

请确保当您在Xcode中选择该文件时,其“目标成员资格”部分已设置(属性窗口中最左边的选项卡) – borrrden

+0

这样做后,我没有收到错误,但声音无法播放。我给出的路径是'file://localhost/var/mobile/Applications/FAA680BA-162E-4E58-A22B-3E2F139A4368/RemindMe.app/Alarm.caf' – Camus

+1

我敢打赌,它不玩的原因是因为它会超出范围并在有机会之前被释放。让它成为一个实例变量,以便它坚持到来。 – borrrden

回答

0

我用这样的事情时,该文件是在一个特定的文件夹:

// Build URL to the sound file we are going to play 
NSURL *sound_file = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:sound_file_name ofType:@"mp3" inDirectory:directory]]; 

// Play it 
audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:sound_file error:nil]; 
audio_player.delegate = self; 
[audio_player play]; 
[sound_file release]; 

sound_file_name是不带扩展名的文件名名称:@"success"

directory是一样的东西: @"media/sound_effects"

0

添加此项并查看程序是否识别文件存在。

NSLog(@"File Exists:%d",[[NSFileManager defaultManager] fileExistsAtPath:fileName]);

如果存在的话它会打印出1。如果不确定你有合适的文件名(大小写)。

+0

我做了,它说1. – Camus

+1

尝试'NSError *错误; AVAudioPlayer * audioFile = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; NSLog(@“Error%@”,[error description]);' –

2

只要遵循两个简单的步骤

第一步:

UIViewController.h

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

@property(nonatomic, retain) AVAudioPlayer *player; 

第2步:

UIViewController.m

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sound" 
                 ofType:@"m4a"]; 
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; 

_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL]; 
[_player setVolume:1.0]; 
[_player play]; 

菊st确保AVAudioPlayer属性必须是非原子的并保留。

0

确保您导入了您的audiotoolbox框架,然后编写以下内容。这是我用来播放简单的声音

#import <AudioToolbox/AudioToolbox.h> 

CFBundleRef mainBundle = CFBundleGetMainBundle(); 
CFURLRef soundFileURLRef; 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"Your sound here", CFSTR ("mp3"), NULL); 

UInt32 soundID; 
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID); 
AudioServicesPlaySystemSound(soundID); 

如果你有任何困惑,让我知道。