播放音频 iOS Objective-C
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11525942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Play Audio iOS Objective-C
提问by Lagoo87
I'm trying to get an audio file playing in my iOS app. This is my current code
我正在尝试在我的 iOS 应用程序中播放音频文件。这是我当前的代码
NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a", [[NSBundle mainBundle] resourcePath]];
NSLog(@"%@",soundFilePath);
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer setVolume:1.0];
audioPlayer.delegate = self;
[audioPlayer stop];
[audioPlayer setCurrentTime:0];
[audioPlayer play];
I've being checking a bunch of other posts but they all generally do the same thing. I'm not getting an error, but I don't hear any audio playing on the simulator or device.
我正在检查一堆其他帖子,但它们通常都做同样的事情。我没有收到错误消息,但我没有听到模拟器或设备上播放的任何音频。
This is the path I get for the audio file on the simulator
这是我在模拟器上得到的音频文件的路径
/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/long-numbered-thing/BookAdventure.app/test.m4a
Any help is appreciated!
任何帮助表示赞赏!
回答by bddicken
Maybe you should try using the NSBundle
method pathForResource:ofType:
method to create the path to the file.
也许您应该尝试使用NSBundle
methodpathForResource:ofType:
方法来创建文件的路径。
The following code should successfully play an audio file. I have only used it with an mp3
, but I imagine it should also work with m4a
. If this code does not work, you could try changing the format of the audio file. For this code, the audio file is located in the main project directory.
以下代码应成功播放音频文件。我只将它与 一起使用mp3
,但我想它也应该与m4a
. 如果此代码不起作用,您可以尝试更改音频文件的格式。对于此代码,音频文件位于主项目目录中。
/* Use this code to play an audio file */
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite
[player play];
EDIT
编辑
Ok, so try this:
好的,试试这个:
NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a",[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite
[player play];
Also, make sure you do the proper imports:
另外,请确保您进行了正确的导入:
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
回答by Mustafa Karaku?
You need to store a strongreference to 'AVAudioPlayer'
您需要存储对“AVAudioPlayer”的强引用
@property (strong) AVAudioPlayer *audioPlayer;
And if you are sure that your audio file is in following Bundle Resources, it should play.
如果您确定您的音频文件在以下捆绑资源中,它应该播放。
Project>Build Phases>Copy
项目>构建阶段>复制
回答by MaxEcho
To play file with extension .caf, .m4a, .mp4, .mp3,.wav, .aif
播放扩展名为 .caf、.m4a、.mp4、.mp3、.wav、.aif 的文件
Download following two files from GitHub
从GitHub下载以下两个文件
SoundManager.h
SoundManager.m
Add these files to your project
将这些文件添加到您的项目中
Also add audio files to resource folder (sample files)
还将音频文件添加到资源文件夹(示例文件)
mysound.mp3, song.mp3
Import header file in desired file
在所需文件中导入头文件
#import "SoundManager.h"
And add following two lines in -(void)viewDidLoad
并在-(void)viewDidLoad 中添加以下两行
[SoundManager sharedManager].allowsBackgroundMusic = YES;
[[SoundManager sharedManager] prepareToPlay];
Use following line to play sound (mysound.mp3)
使用以下行播放声音 (mysound.mp3)
[[SoundManager sharedManager] playSound:@"mysound" looping:NO];
Use following line to stop the sound (mysound.mp3)
使用以下行停止声音 (mysound.mp3)
[[SoundManager sharedManager] stopSound:@"mysound"];
Also you can play music (song.mp3) as
您也可以播放音乐(song.mp3)作为
[[SoundManager sharedManager] playMusic:@"song" looping:YES];
And can be stop music as
并且可以停止音乐作为
[[SoundManager sharedManager] stopMusic];
Complete Documentation is on GitHub
完整的文档在 GitHub 上
回答by Anooj VM
First import this framework to your file
首先将此框架导入到您的文件中
#import <AVFoundation/AVFoundation.h>
Then declare an instance of AVAudioPlayer
.
然后声明一个AVAudioPlayer
.
AVAudioPlayer *audioPlayer;
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Name of your audio file"
ofType:@"type of your audio file example: mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
回答by Subathra D
To play your bundle audio file using below code if you generate the system sound ID
如果您生成系统声音 ID,则使用以下代码播放您的捆绑音频文件
for(int i = 0 ;i< 5;i++)
{
SystemSoundID soundFileObject;
NSString *audioFileName = [NSString stringWithFormat:@"Alarm%d",i+1];
NSURL *tapSound = [[NSBundle mainBundle] URLForResource: audioFileName
withExtension: @"caf"];
// Store the URL as a CFURLRef instance
CFURLRef soundFileURLRef = (__bridge CFURLRef) tapSound;
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (
soundFileURLRef,
&soundFileObject
);
[alarmToneIdList addObject:[NSNumber numberWithUnsignedLong:soundFileObject]];
}
You can play the sound by using below code
您可以使用以下代码播放声音
AudioServicesPlaySystemSound([[alarmToneIdList objectAtIndex:row]unsignedLongValue]);
To achieve this below framework need to add in your Xcode
要实现以下框架,需要在您的 Xcode 中添加
AudioToolbox
音频工具箱
Finally below header files are needs to be import in controller
最后需要在控制器中导入下面的头文件
#import AudioToolbox/AudioToolbox.h
#import AudioToolbox/AudioServices.h
回答by Niall Kiddle
Updated for Swift 4Playing from main bundle - iOS 11 only
更新了 Swift 4Playing from main bundle - 仅限 iOS 11
import AVFoundation
var player: AVAudioPlayer?
The following code loads the sound file and plays it, returning an error if necessary.
以下代码加载声音文件并播放,如有必要,返回错误。
guard let url = Bundle.main.url(forResource: "test", withExtension: "m4a") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
guard let player = player else { return }
player.play()
} catch let error {
// Prints a readable error
print(error.localizedDescription)
}
回答by mohammad shahid
Swift 4.2
斯威夫特 4.2
var soundFilePath = "\(Bundle.main.resourcePath ?? "")/test.m4a"
var soundFileURL = URL(fileURLWithPath: soundFilePath)
var player = try? AVAudioPlayer(contentsOf: soundFileURL)
player?.numberOfLoops = -1 //Infinite
player?.play()