[英]How to play audio file ios
我正在尝试播放音频文件,但我可以使用它。 我导入了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
我将文件复制到支持文件文件夹,因此文件就在那里。
你们能帮助我吗?
谢谢
只需按照两个简单的步骤
第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属性必须是非原子的并保留。
当文件在特定文件夹中时,我使用类似的东西:
// 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"
添加此项并查看程序是否识别该文件存在。
NSLog(@"File Exists:%d",[[NSFileManager defaultManager] fileExistsAtPath:fileName]);
如果存在,它将打印1。 如果不确定您具有正确的文件名(案例重要)。
确保导入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);
如果您对此有任何疑惑,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.