I have some mp3 files in my resources folder, how can i play those mp3 files? I just know their name.
Just to supplement #Georg's answer.
As you can see from the doc, -URLForResource:withExtension: is available only since 4.0. As 3.x is still widespread, it's better to use the backward-compatible methods:
By converting a path to NSURL:
NSString* path = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"mp3"];
NSURL* url = [NSURL fileURLWithPath:path];
....
or, by CoreFoundation methods:
CFURLRef url = CFBundleCopyResourceURL(CFBundleGetMain(),
CFSTR("myFile"), CFSTR("mp3"), NULL);
....
CFRelease(url);
You can use the AVAudioPlayer. To get the URL for the files use NSBundles -URLForResource:withExtension: (or downward compatible alternatives, see Kennys answer):
NSURL *url = [[NSBundle mainBundle] URLForResource:#"myFile" withExtension:#"mp3"];
NSError *error = 0;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
// check error ...
[player play];
// ...
And don't forget to read the Multimedia Programming Guides section on using audio.
Related
I am using below code
// it is showing nil for path
NSString *path = [[NSBundle mainBundle] pathForResource:#"filetext.doc" ofType:nil];
NSURL *url1 = [NSURL fileURLWithPath:path];
// it is showing working
NSString *path = [[NSBundle mainBundle] pathForResource:#"filetext.txt" ofType:nil];
NSURL *url1 = [NSURL fileURLWithPath:path];
Please help what is the issue
According to the docs, the method returns nil if the file cannot be found. The conclusion, therefore, is that the file is missing. Check your project's Build Phases/Copy Bundle Resources to ensure that the file is actually present because in all likelihood it is not.
I have been able to read a file called 'exerciseA.htm' from a live url. but now i need to bring the file locally add it to the project and read it from there. I have dragged the file into xcode to add it. Now i need to read its contents to a string, however the following doesnt seem to work:
NSString* exerciseAPage = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"exerciseA" ofType:#"htm"] encoding:NSUTF8StringEncoding error:&error];
[exerciseWebViewA loadHTMLString:exerciseAPage baseURL:nil];
Is this the correct way to load local htm file to a webview?
I do it the following way (Which is basically the same as you specify):
NSURL *url = [[NSBundle mainBundle] URLForResource:nameOfHtmlFile withExtension:#"html"];
NSError *error;
NSString *contentString = [NSString stringWithContentsOfURL:url encoding:NSStringEncodingConversionAllowLossy error:&error];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.webView loadHTMLString:contentString baseURL:baseUrl];
Hope this helps
Alex
I'm trying to get an audio file playing in my iOS app. This is my current code
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!
Maybe you should try using the NSBundle method pathForResource:ofType: method to create the path to the file.
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.
/* 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>
You need to store a strong reference to '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
To play file with extension .caf, .m4a, .mp4, .mp3,.wav, .aif
Download following two files from 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
[SoundManager sharedManager].allowsBackgroundMusic = YES;
[[SoundManager sharedManager] prepareToPlay];
Use following line to play sound (mysound.mp3)
[[SoundManager sharedManager] playSound:#"mysound" looping:NO];
Use following line to stop the sound (mysound.mp3)
[[SoundManager sharedManager] stopSound:#"mysound"];
Also you can play music (song.mp3) as
[[SoundManager sharedManager] playMusic:#"song" looping:YES];
And can be stop music as
[[SoundManager sharedManager] stopMusic];
Complete Documentation is on GitHub
First import this framework to your file
#import <AVFoundation/AVFoundation.h>
Then declare an instance of 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];
To play your bundle audio file using below code if you generate the system sound 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
AudioToolbox
Finally below header files are needs to be import in controller
#import AudioToolbox/AudioToolbox.h
#import AudioToolbox/AudioServices.h
Updated for Swift 4
Playing from main bundle
- iOS 11 only
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)
}
Swift 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()
I need to play some system sound when users click button in my application which is running on iPad. How to implement it in iOS?
If you want to play a short sound (shorter than 30 sec), you can do it easily like this:
Note: You'll have to add AudioToolbox framework and import it (#import <AudioToolbox/AudioToolbox.h>)
SystemSoundID mySSID;
NSString *path = [[NSBundle mainBundle] pathForResource:#"beep" ofType:#"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: path], &mySSID);
AudioServicesPlaySystemSound(mySSID);
Also note that the file can be:
No longer than 30 seconds in duration
In linear PCM or IMA4 (IMA/ADPCM) format
Packaged in a .caf, .aif, or .wav file
You should use AVAudioPlayer.
There's a great tutorial here on using AVAudioPlayer to play sounds. A very simple example of it's use:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3",dataPath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
NSString *path = [[NSBundle mainBundle] pathForResource:#"gorilla 2" ofType:#"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate=self;
[theAudio play];
I'm new to this, so in an attempt to keep things simple, I'm trying to add sound into my main.m
As far as I know, the following code should work, but when I run it, I get a "Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)" (File not found)"
I've tried it with various audio files and formats - added to the project in Xcode but can't figure out why it isn't finding my G1.wav
AVAudioPlayer *audioPlayer;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"/G1.wav"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
EDIT removed NSBundle and mainBundle references - my misunderstanding
You might be better off with this:
NSString *path = [[NSBundle mainBundle] pathForResource:#"G1" ofType:#"wav"];
NSURL *url = [NSURL fileURLWithPath:path];
...
Using pathForResource:ofType: you don't have to worry about where in the hierarchy of your bundle the file is. The API call figures it out. And in your code, whatever resourcePath is returning is clearly not the right path.
You might add some NSLog() calls here and there to see what is really happening, as well.