[英]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.