xcode 在 IOS 上播放声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14303842/
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
Playing sounds on IOS
提问by Alessandro
I want to play a sound when a button is pressed. I tried this:
我想在按下按钮时播放声音。我试过这个:
-(void)PlayClick
{
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"BubblePopv4"
ofType:@"mp3"]];
AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[click play];
}
…and imported #import <AudioToolbox/AudioToolbox.h>
and #import <AVFoundation/AVFoundation.h>
...并进口#import <AudioToolbox/AudioToolbox.h>
和#import <AVFoundation/AVFoundation.h>
but for some reason the sound is not playing. The name and type are right because the file I added to the project is "BubblePopv4.mp3". The volume on the iPad is on maximum, and the sound plays fine on iTunes! Any ideas?
但由于某种原因,声音没有播放。名称和类型是对的,因为我添加到项目中的文件是“BubblePopv4.mp3”。iPad 上的音量已调到最大,iTunes 上的声音也很好!有任何想法吗?
采纳答案by Reno Jones
Leave it, Don't do it in a new Class, simple stuff for you:
离开它,不要在一个新的类中做,简单的东西给你:
- (void)playSoundWithOfThisFile:(NSString*)fileNameWithExtension {
// Eg - abc.mp3
AVAudioPlayer *audioPlayerObj;
NSString *filePath;
filePath= [[NSString stringWithFormat:@"%@", [[NSBundle mainBundle] resourcePath]] retain];
if(!audioPlayerObj)
audioPlayerObj = [AVAudioPlayer alloc];
NSURL *acutualFilePath= [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",filePath,fileNameWithExtension]];
NSError *error;
[audioPlayerObj initWithContentsOfURL:acutualFilePath error:&error];
[audioPlayerObj play];
}
回答by Reno Jones
Do this:
做这个:
In .h file:
在 .h 文件中:
Use this delegate - <AVAudioPlayerDelegate>
#import "AVFoundation/AVAudioPlayer.h"
AVAudioPlayer *audioPlayerObj;
NSString *filePath;
In .m file , In some method:
在 .m 文件中,在某些方法中:
filePath= [[NSString stringWithFormat:@"%@", [[NSBundle mainBundle] resourcePath]] retain];
if(!audioPlayerObj)
audioPlayerObj = [AVAudioPlayer alloc];
And add these two methods:
并添加这两个方法:
- (id)initWithFileName:(NSString*)fileNameWithExtension {
if ((self = [super init])) {
NSURL *acutualFilePath= [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",filePath,fileNameWithExtension]];
NSError *error;
[audioPlayerObj initWithContentsOfURL:acutualFilePath error:&error];
}
return self;
}
- (void)playSound {
[audioPlayerObj play];
}
You can pass the filename to this Method - initWithFileName
您可以将文件名传递给此方法 - initWithFileName
and then call playSound method to play sound for you.
然后调用 playSound 方法为您播放声音。
Hope this helps.
希望这可以帮助。
回答by Basem Saadawy
Replace url initialization with:
将 url 初始化替换为:
NSURL* musicFile = [NSURL initFileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"BubblePopv4"
ofType:@"mp3"]];