3

我正在尝试播放音频文件,但我可以让它工作。我导入了AVFoundation框架。

这是代码:

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

我将文件复制到支持文件文件夹中,因此文件在那里。

你们能帮帮我吗?

谢谢

4

4 回答 4

2

只需遵循两个简单的步骤

步骤1:

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];

只需确保 AVAudioPlayer 属性必须是非原子的并保留。

于 2015-04-12T15:55:05.643 回答
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"

于 2012-10-02T03:48:31.973 回答
0

添加这个并查看程序是否识别出该文件存在。

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

如果存在,它将打印一个 1。如果不确定你有正确的文件名(大小写很重要)。

于 2012-10-02T03:48:43.267 回答
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);

如果您对此有任何困惑,请告诉我。

于 2015-04-12T16:56:50.223 回答